Cool code : async function always return a promise

Posted on: 2017-05-13

There is really just two things to know to understand javascript async/await :

  • an async function return a promise
  • await always wait for a promise to 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 ! 😉