Function using promises:
function myAsyncFunction() {
return aFunctionThatReturnsAPromise()
// doSomething is a sync function
.then(result => doSomething(result))
.catch(handleError);
}
So here is when Async/Await enter in action in order to get cleaner our function:
async function myAsyncFunction() {
let result;
try {
result = await aFunctionThatReturnsAPromise();
} catch (error) {
handleError(error);
}
// doSomething is a sync function
return doSomething(result);
}
So the keyword async
would be similar to write return new Promise((resolve, reject) => {...}
.
And await
similar to get your result in then
callback.
Here I leave a pretty brief gif that will not left any doubt in mind after seeing it: