Changing My Callbacks, Promise To Async Await
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:
async function firstSecondThird() {
let firstPromiseValue = await first();
console.log(firstPromiseValue);
let secondPromiseValue = await second();
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) => {
return new Promise((resolve, reject) => {
resolve('first ');
});
};
const second = async (value) => {
return new Promise((resolve, reject) => {
resolve(value + 'second ');
});
};
const third = async (value) => {
return new Promise((resolve, reject) => {
resolve(value + 'third');
});
};
first('').then(second).then(third).then( value => console.log(value) );
const first = async () => {
return new Promise((resolve, reject) => {
resolve('first ');
});
};
const second = async () => {
return new Promise((resolve, reject) => {
resolve('second ');
});
};
const third = () => {
return 'third';
};
async function main() {
let firstValue = await first();
let secondValue = await second();
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"