From promise to ES6 async
We saw that there are many ways to do asynchronous code in javascript from callback function to promise, but now with ES6 there is a new way to do asynchronous code with the (async, await) keywords. This ES6 syntax must be used with Promise so this is a not a new way to produce async code but a better way to consume Promise by avoid all this
thenandcatchmethod.
Async function
const getId = new Promise( (resolve, reject) => {
setTimeout( () => {
resolve( [100, 200, 300, 400] );
}, 1500 );
} );
const getIdAw = async () => {
const Id = await getId;
console.log(Id);
};
getIdAw();
- Like we said
asyncfunctions is a new way to consumePromise. - You can create an
asyncfunction simply by using theasynckeywords in front of your function, this will tell to the javascript engine this function will run in background. - Remember that we said that inside an
asyncfunction we can access the result of ourPromisefunction (resolve, reject), in order to do that you have to use theawaitkeywords and called yourPromise. - So in summary we can tell that the
getIdAwfunction is an asynchronous function who runs in the background of our code and wait forPromiseto be resolved or not. - You can use inside your
asyncfunction ordinary code which means withoutawaitbut the result will always be convert to aPromise.
Current errors
This is a list of the main errors that you can meet:
Note: I'm not a wizard there is maybe some issue that you notice above so fell free to open an issue in the github repo if you find a new error not mentioned above.