Skip to content Skip to sidebar Skip to footer

Changing My Callbacks, Promise To Async Await

My code: Callbacks: const first = () => { console.log('first'); }; const second = (callback) => { setTimeout(() => { console.log('second'); callback(); }, 2

Solution 1:

How to convert this above code using async await?

async/await is not a replacement for promises, it is a replacement for then() and catch(). You'd still be using promises. So you'd take the first, second and third definition from your Promises section, and then:

asyncfunctionfirstSecondThird() {
  let firstPromiseValue = awaitfirst();
  console.log(firstPromiseValue);
  let secondPromiseValue = awaitsecond();
  console.log(secondPromiseValue);
  third(); // not a promise, no need to await
}
firstSecondThird();

Which is the good flow control for javascript applications?

Objectively, none of them are better; but async/await is the most readable, callbacks the most explicit (with then code being in the middle).

What about some async library which uses methods like async.waterfall, etc..

Promises generally do everything those libraries do, and also got selected to be standardised. You may forget about those libraries unless you are maintaining old code that requires them.

By the way, is my above code is ok or not?

It seems to do what you want it to do, more or less, without obvious problems in efficiency or legibility. I'd say it's OK.

Solution 2:

How to convert this above code using async await?

Using async/await is another way to use Promises. It's most nice visualy because you don't lost in then/catch but you can use it. Here you have two examples. First one with then and second one without.

const first = async (value) => {
  returnnewPromise((resolve, reject) => {
    resolve('first ');
  });
};
const second = async (value) => {
  returnnewPromise((resolve, reject) => {
    resolve(value + 'second ');
  });
};
const third = async (value) => {
  returnnewPromise((resolve, reject) => {
    resolve(value + 'third');
  });
};


first('').then(second).then(third).then( value =>console.log(value) );

const first = async () => {
  returnnewPromise((resolve, reject) => {
    resolve('first ');
  });
};
const second = async () => {
  returnnewPromise((resolve, reject) => {
    resolve('second ');
  });
};
constthird = () => {
  return'third';

};

asyncfunctionmain() {
  
  let firstValue = awaitfirst();
  
  let secondValue = awaitsecond();
  
  let thirdValue = third();
  
  return  firstValue + ' ' + secondValue + ' ' + thirdValue;
}

main()
  .then(console.log)
  .catch(err => { console.log('Error:', err) });

Which is the good flow control for javascript applications?

Normally when you need to use Promise in the middle of a function or multiple async calls fo functions.

What about some async library which uses methods like async.waterfall, etc..

I don't know about any library to use async/await. Sorry!

Post a Comment for "Changing My Callbacks, Promise To Async Await"