For a long time, JavaScript developers had to rely on callbacks to deal with asynchronous code. As a result, many of us have gone through callback hell, feeling scoundrel when confronted with such functions
The good news is that JavaScript provides a way to reply to.then(), and a lot of people are using it
Now, with the latest addition of Async/Await, writing JavaScript code will become even more elegant!
What is Async/Await?
Async/Await is a long awaited JavaScript feature that makes using asynchronous functions more enjoyable and easier to understand. It is built on Promises and is compatible with all existing Promise based apis
The name comes from async and await — two key words that help us clean up asynchronous code:
Async- Declare an Async function someName (){… })
- Automatically converts an ordinary function into a promise
- When an asynchronous function is called, the asynchronous content is then returned when the asynchrony is complete
- Await is allowed in asynchronous functions
Await- Suspends the execution of async functions
- When placed in front of a Promise, forces the rest of the code to wait until the Promise is complete and a result is returned
- It only works on Promises, not callback
- Can only be used inside async functions
Let’s look at a simple example
Suppose we want to get some JSON files from the server. We will write a use axios library function, and to tutorialzine.com/misc/files/… Send an HTTP GET request. We have to wait for the server to respond, so the HTTP request is naturally asynchronous
Below we can see two implementations of the same function. First use Promises, then the second use Async/Await
// Promise
function getJSON(){
// To block the function, we manually create a promise.
return new Promise( function(resolve) {
axios.get('https://tutorialzine.com/misc/files/example.json')
.then( function(json) {
// Get the returned JSON data in.then
// We use resolve to return the result
resolve(json);
});
});
}
// Async/Await
// The async keyword automatically creates a new Promise and returns it.
async function getJSONAsync(){
The // await keyword keeps us from writing then().
let json = await axios.get('https://tutorialzine.com/misc/files/example.json');
// The result of the GET request is available in the JSON variable.
// Get data just like in a regular synchronization function
return json;
}
Copy the code
Obviously the Async/Await version of the code is shorter and easier to read. These two functions are identical except for the syntax they use — they both return Promises and use AXIos’ JSON response parsing. We can call our async function like this:
The async return is itself a Promise
getJSONAsync().then( function(result) {
// Do something with result.
});
Copy the code
Does Async/Await make promises obsolete?
No, not at all. While using Async/Await, we are still using Promises under the hood. Fully understanding promises will actually help you in the long run, so it’s highly recommended
Even Async/Await doesn’t work in some cases, we have to go back to Promises for help. In one case, we need to make multiple independent asynchronous calls and wait for them all to complete
If we try to implement this functionality with async and await, the following will happen:
async function getABC() {
let A = await getValueA(); // getValueA takes 2 seconds
let B = await getValueB(); // getValueB takes 4 seconds
let C = await getValueC(); GetValueC takes 3 seconds
return A*B*C;
}
Copy the code
Each await await will wait for the result returned before await await. Because we only call one function at a time, the entire function takes 9 seconds from start to finish (2 + 4 + 3)
This is not the best solution because the three variables A, B, and C do not depend on each other. In other words, we don’t need to know the value of A until we get to B. We can get them all at the same time, reducing the wait time by a few seconds
Send all requests at the same time. This will ensure that we still have all the results before proceeding, but the asynchronous calls will be requested in parallel rather than one after another
async function getABC() {
// promise.all () allows us to send multiple requests simultaneously, of type an array
let results = await Promise.all([ getValueA, getValueB, getValueC ]);
return results.reduce((total,value) = > total * value);
}
Copy the code
This way, the function takes much less time to run. The getValueA and getValueC calls will have completed by the end of getValueB, effectively reducing the execution time to the time of the slowest request (getValueB-4 seconds), rather than the sum
Error handling in Async/Await
Another advantage of Async/Await is that it allows us to catch any unexpected errors in a nice try/catch block. Just wrap Await like this:
async function doSomethingAsync(){
try {
// Async may fail to send
let result = await someAsyncCall();
}
catch(error) {
// If it fails, catch the error}}Copy the code
The Catch clause will handle errors raised by waiting asynchronous calls or any other failing code we write in the try block
We can also catch errors while executing async functions if the situation requires it. Because all asynchronous functions return Promises, we can simply include one. When the catch () event handler is called.
async function doSomethingAsync(){
// This async call may fail.
let result = await someAsyncCall();
return result;
}
// Use catch to catch errors
doSomethingAsync().
.then(successHandler)
.catch(errorHandler);
Copy the code
conclusion
With the addition of Async/Await, the JavaScript language has taken a huge leap forward in code readability and ease of use. The ability to write asynchronous code similar to regular synchronous functions will appeal to beginners, JavaScript developers, and experienced coders
The article belongs to translation, author: Mr. Yang, English original