Async - async/await
Okay you have delt with callbacks, and seen how messy and complex that can get quickly, you have dealt with promises and the power they bring to the table and maybe also experienced some frustration with how once you start with something in a promise it sometimes seems like everything is promises after that. async and the await function might be just what you were waiting for. Its definitely not a catch all or replacement for plain promises but it can help clean up code a lot sometimes.
async keyword
async keyword is used to identify a function that is async.
for example: async function myfunc(){ return; }
also it can be used with arrow functions: let myfunca = async () => { return; }
this can be used anywhere a function is defined.
this async function now returns a promise and that promise can be used either with the await command or with any of the promise methods we talked about before.
await keyword (only works inside an async function)
This pauses execution and waits for the promise to resolve before it’ll continue.
async func1() {
let something = await func2();
let someJson = await fetch('/users/person.json');
return;
}
async func2(){
let myProm = await new Promise((resolve, reject) => setTimeout(resolve, 3000));
return myProm;
}
func1();
Next Article: Modules 1