
Async/Await Syntax
The async/await keywords are a new syntax, introduced in ES2017, to work with promises in JavaScript.
To write an async function you start with the async keyword, the function name and the statements inside of the function. The return value is a promise that will be resolved with the value returned by the function or rejected with an exception from, or uncaught within, the async function.
async function firstAsyncFunc() {
return 'something';
}
firstAsyncFunc();
//Promise {<resolved>: "something"}
//__proto__: Promise
//[[PromiseStatus]]: "resolved"
//[[PromiseValue]]: "something"The await keyword waits for a Promise to return a result and can only be used in an async function. Async functions can have zero or more await expressions. In the example below the asyncWithAwait function will wait until secondAsyncFunc function resolves before console logging the result variable.
async function secondAsyncFunc() {
console.log('This is the start of the promise function.');
return new Promise(resolve => {
setTimeout(function() {
resolve('This is the resolve.');
console.log("This promise is done");
}, 1000);
});
}
async function asyncWithAwait() {
console.log('This is the start of the await.');
let result = await secondAsyncFunc();
console.log(result);
}
asyncWithAwait();
//This is the start of the await.
//This is the start of the promise function.
//Promise {<pending>} (pending for 1 second)
//This promise is done
//This is the resolve.
Now let's see how to update promise chaining with the async/await keywords.
The old way:
const getProductInfo = () => {
return fetch('/products.json')
.then(response => response.json())
.then(products => products[0])
.then(product => fetch(`/products/${product.id}`))
.then(productResponse => productResponse.json())
}
getProductInfo();The async/await way:
async function getUserInfo(){
const response = await fetch('/products.json');
const products = await response.json();
const product = await products[0];
const productResponse = await fetch(`/products/${product.id}`);
const productsData = await productResponse.json();
return productsData;
}
getProductInfo();Error handeling:
If a promise successfully resolves then the await promise will return a result. In the case that a promise is rejected an error will be thrown. Since it might take some time for a promise to resolve the try/catch syntax should be used.
async function dealingWithErrors(){
try{
let response = await fetch('/error-end-point.json');
let product = await response.json();
} catch(err) {
console.log(err);
}
}
dealingWithErrors();In the case of an error the catch block will console log the error.
TLDR;
- Async keyword
- when placed in front of a function it returns a promise
- allows you to use the await keyword
- Await keyword
- makes the javascript wait until the promise resolves
- if the promise is rejected and error will be thrown
- otherwise you will get a result
- makes the javascript wait until the promise resolves
- Using the async/await syntax reduces the use of promise.then/catch syntax. In some cases you might use Promise.all() if you have multiple promises you are waiting on before a result can be returned.