Instead of using promises for async tasks, you can do the same thing using the new async and await keywords in JavaScript.
Consider this method:
main(a) {
return Promise.resolve(a)
.then(a => asyncTaskA(a))
.then(b => asyncTaskB(b))
.then(c => asyncTaskC(c))
.catch(e => console.log(e))
.finally(() => cleanUp());
}
You can rewrite it much simpler in this way:
async main(a) {
try {
let b = await asyncTaskA(a);
let c = await asyncTaskA(b);
return await asyncTaskA(c);
} catch (e) {
console.log(e)
}
cleanUp();
}
This is certainly a more elegant and simpler approach for writing async code.
It should be remembered that await can only be used inside a function that has been marked with the async keyword. This keyword shows that the function returns a promise and thus is an async function.