`async/await` in Javascript

async/await explained
async/await is a better, shorter and more readable way to write promises/asynchronous operations. async is a function (is always applied onto a function) and await is a keyword permitted inside the async function, making sure that the Javascript waits until the promise is settled and return its return.
When we use async/await, we rarely need .then, because await handles the waiting for us.
Example of a promise with fetch:
const promise = fetch('https://jsonplaceholder.typicode.com/todos/1', {})
.then(function(response) { // then always produces a new promise and thus permits chaining more then
return response.json(); // returns a promise which resolves with the result of parsing the body text as JSON
})
.then(function(data) { // the return from the first promise is passed as argument onto the second promise
console.log(data);
});
Example of the async/await for the above promise:
async function getResponse() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {}); // await added to wait until the settlement of the first promise
console.log('Got the response!');
const data = await response.json(); // another await added for the 2nd then
console.log(data);
}
getResponse();
Each time there is a
thenstatement, there is anawaitstatement in theasync/await.
To listen to the reject state of the async/await statement, we use the try/catch. Example:
async function getResponse() {
try {
const response = await fetch('https://jsonplaceholder.typicode/todos/1', {}); // .com removed to purposely get into the reject state
console.log('Got the response!');
const data = await response.json(); // another await added for the 2nd then
console.log(data);
} catch(err) {
console.log('Got an error!');
}
}
getResponse();
async/await works well with Promise.all
When we need to wait for multiple promises, we can wrap them in Promise.all and then await:
// wait for the array of results
let results = await Promise.all([
fetch(url1),
fetch(url2),
fetch(url3)
]);
In the case of an error, it propagates as usual, from the failed promise to Promise.all, and then becomes an exception that we can catch using try..catch around the call.




