Async & Await
The async
and await
keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
Async
An asynchronous function operates asynchronously via the event-loop – the event loop is a constantly running process that monitors both the callback queue and the call stack.
const getData = async() => {
var y = await "Hello World";
console.log(y);
}
console.log(1);
getData();
console.log(2);
Output:
1
2
Hello World
You can mark any JavaScript function with async
; that’s wherethe power of Async-Await lies, it lets you write asynchronous promise-based code that looks like synchronous code.
async function processData(url) {
...
}
Await
Inside the async function is the await
keyword to wait for a promise.
async function fetchData(url) {
const response = await fetch(url);
const data = await response.json();
return data;
}
If we didn’t use await
, the function will return the awaited promise itself instead of a resolved promise!
await
‘s Behavior
- Pauses the execution of an async function and waits for the resolution of a promise
- Resumes execution and returns the resolved value
- Pausing execution is not going to cause blocking behavior
- Valid to use only inside functions marked async
An asynchronous function always returns a promise, always. You can access the data of an asynchronous function by using then
and catch
methods just like you normally would with promises or a fetch API.
Comparing Promises and Async-Await
Async-Await is not meant to replace promises. Rather, it’s syntactic sugar for creating functions that return and wait for promises. So really it’s a supplement to promises.
In the example below, the makeRequest
function creates a promise and returns it.
The processRequest
function also creates a promise and returns it.
function makeRequest(location) {
return new Promise((resolve, reject) => {
console.log(`Making Request to ${location}`)
if (location === 'Google') {
resolve('Google says hi')
} else {
reject('We can only talk to Google')
}
})
}
function processRequest(response) {
return new Promise((resolve, reject) => {
console.log('Processing response')
resolve(`Extra Information + ${response}`)
})
}
To consume the result of those promises, we can do it with then
and catch
, or using async-await.
Using then
and catch
makeRequest('Google')
.then(response => {
console.log('Response received!');
return processRequest(response);
})
.then(processedResponse => {
console.log(processedResponse);
})
.catch(err => {
console.log(err);
})
Using async
and await
async function startRequest() {
try {
const response = await makeRequest('Google');
console.log('Response received');
const processedResponse = await processRequest(response);
console.log(processedResponse);
} catch (err) {
console.log(err);
}
}
startRequest();
As you can see the second approach makes the code is tidier and more readable.
Source: Async-Await tutorial