Async and Await in JavaScript the execution of the code is synchronous. That is, one action can performed at a time. But the behavior is asynchronous, so we have a feeling we can run several blocks of code in parallel. Thanks to the syntax that allows the script not to linger until the result of events. And instead return later, to collect the result. For example, when we send a request in Ajax, we do not wait for it to return. But perform the handling within a callback or promise, and meanwhile. The rest of the script continues to run.
Besides to callback and promise, the new syntax. That enables asynchronous behavior called Async / Await, and it is worth recognizing. That over the next few years more libraries and developers will adopt it.
In this tutorial, we will briefly mention how to use JavaScript asynchronous behavior through callbacks and promises, and then we will continue with an explanation of Async / Await.
Asynchronous code using callback
window.setTimeout( ()=> console.log('text 1'),100);
console.log('text 2');
The result is that line 2 (‘text 2’) is printed before line 1 (‘text 1’). Feel free to try it for yourself.
The second line is printed before the first line because the browser does not delay the execution of the code until the callback ends, this just continues to run, and only then returns to finish the code inside the callback.
It also works without specifying the time that the function has to wait as the second parameter passed to the method:
window.setTimeout(()=> console.log('text 1'));
console.log('text 2');
Why? callback!
Because the code inside the callback is executed after the rest of the script.
This is an especially useful feature when you want to wait for information coming from a remote server. For example, bringing in Ajax information using jQuery:
jQuery.get('https://phpenthusiast.com/dummy-api', (res) => console.log(res));
// The rest of the script
The rest of the script runs, instead of waiting for the information to return, if at all, from the remote server.
The API service in the example, returns a random number between 1 and 6, as in a dice roll.
Asynchronous code using promise
The newest way to get information from a remote server is through the fetch method that returns a promise, i.e. one of two possible outcomes, success or failed.
fetch('https://phpenthusiast.com/dummy-api/')
.then((res) => console.log(res))
.catch((error) => console.log(error));
Success, which means returning the requested information, is handled in the then block.
And cases of error, are handled using a catch block.
One of the benefits of using promises is that you can connect them to each other in a chain of promises that run one after the other. For example, to extract information in the JSON format that comes with the fetch() method, we will add the json() method to the string, which also returns a promise().
fetch('https://phpenthusiast.com/dummy-api/')
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.log(error))
Beyond the elegance of the syntax, the errors, no matter what promises they make, are handled by the same block catch.
To promise we can thread the all() method that waits for the end of several events, for example, if we want to get information from several different sources. And in our example, we want to call the API service twice to mimic the roll of two dice:
const api = 'https://phpenthusiast.com/dummy-api/';
let dice_1 = fetch(api);
let dice_2 = fetch(api);
Promise.all([dice_1,dice_2])
// …
To extract the info efficiently you need to use the map() method:
let dice_1 = fetch(api);
let dice_2 = fetch(api);
Promise
.all([dice_1,dice_2])
.then(responses => Promise.all(responses.map(res => res.json())))
.then(results => console.log(`And the result is: ${results[0].random}, ${results[1].random}`))
.catch(()=>console.log('can\'t throw the dices'));
And the same result can be achieved using Async / Await syntax.
Asynchronous code using Async / Await
The syntax of Async / Await is simpler and more readable than a promise, and it uses the keywords async and await.
Add the async keyword before the function and the await keyword within the function.
const diceThrower = async () => {
let dice_1 = await dice();
}
Its function calls the await returns promise:
const api = 'https://phpenthusiast.com/dummy-api/';
const dice = () => {
return fetch(api).then(res => res.json());
}
And the await waits for all service calls to be answered to run the rest of the code:
const diceThrower = async () => {
let dice_1 = await dice();
let dice_2 = await dice();
console.log(`The result is: ${dice_1.random}, ${dice_2.random}`);
}
The code is much more readable, and to handle errors we will wrap it in a try… catch:
const diceThrower = async () => {
try {
let dice_1 = await dice();
let dice_2 = await dice();
console.log(`The result is: ${dice_1.random}, ${dice_2.random}`);
} catch(err) {
console.log(err);
}
}
This is the full example:
const api = 'https://phpenthusiast.com/dummy-api/';
const dice = () => {
return fetch(api).then(res => res.json());
}
const diceThrower = async () => {
try {
let dice_1 = await dice();
let dice_2 = await dice();
console.log(`The result is: ${dice_1.random}, ${dice_2.random}`);
} catch(err) {
console.log(err);
}
}
diceThrower();