Cool code : async function always return a promise
There is really just two things to know to understand javascript async/await :
- an
asyncfunction return apromise awaitalways wait for apromiseto be resolved and gives you the value it resolved with (so it raises an error if the promise was rejected)
'use strict';
const myAsyncFunc = async function () {
await Promise.resolve();
console.log(`In myAsyncFunc`);
}
const failFunc = async function () {
await Promise.reject();
console.log(`In failFunc`);//wont be executed
}
myAsyncFunc()
.then(() => {
console.log(`After myAsyncFunc`);
})
.then(failFunc)
.catch(err => {
console.log(`Catch error in failFunc`);
})
}
Result :
In myAsyncFunc
After myAsyncFunc
Catch error in failFunc
Of course we can also resolve promises with try/catch ! 😉