Async / Await
Before
const fetchSomething = () => new Promise((resolve) => {
setTimeout(() => resolve('future value'), 500);
});
const promiseFunc = () => new Promise((resolve) => {
fetchSomething().then(result => {
resolve(result + ' 2');
});
});
promiseFunc().then(res => console.log(res));
After
const fetchSomething = () => new Promise((resolve) => {
setTimeout(() => resolve('future value'), 500);
});
async function asyncFunction() {
const result = await fetchSomething(); // returns promise
// waits for promise and uses promise result
return result + ' 2';
}
asyncFunction().then(result => console.log(result));
Dissecting the code examples above, inside an async
function, you can use await
keyword which will wait for the inner async function fetchSomething
to end before proceeding to next instruction.