For the longest time, JavaScript developers had to rely on callbacks to deal with asynchronous code.
As a result, many of us have gone through callback hell…

Thank Goodness. Then (or should we say. Then) came Promises. They provided a more organized alternative to callbacks, and most communities quickly switched to them. Now, with the latest addition of Async/Await, writing JavaScript code is about to get better!

What is async/await?

async– Declare an async function someName(){… })

  1. Automatically convert regular functions to promises;

  2. When the asynchronous functions being called are resolved to what is returned in their bodies;
  3. Asynchronous functions can use await

await– Suspend the asynchronous function. (var result = await someAsyncCall();)

  1. When placed before a Promise call, await forces the rest of the code to wait for the Promise to complete and return the result;

  2. Await is only for Promises, it is not for callbacks;
  3. Await can only be used inside async functions

Here’s a simple example that hopefully solves the problem:

Suppose we want to get some JSON files from the server. We’ll write a library that uses AXIOS and sends an HTTP GET request

The function of https://tutorialzine.com/misc/files/example.json. We have to wait for the server to respond, so the HTTP request is naturally asynchronous.

We’ll see the same function performed twice. Use Promise first, and Async/Await a second time

// Promise

function getJSON// Create a Promisereturn new Promise( function(resolve) {
        axios.get('https://tutorialzine.com/misc/files/example.json')
            .then( functionResolve (json) {resolve(json); }); }); } // Async/Await// The async keyword will automatically create and return Promise asyncfunction getJSONAsync() {/ /waitThe keyword saves us from writing.then () blockslet json = await axios.get('https://tutorialzine.com/misc/files/example.json'); // The result of the request is assigned to the JSON variable and returnedreturn json;
}Copy the code

Obviously, the Async/Await version of the code is shorter and easier to read. The two functions are identical except for the syntax used – they both return Promises and are parsed using AXIos’ JSON response. We can call our asynchronous function like this:

GetJSONAsync ().then(function(result) {// do something with result. });Copy the code

Whether Async/Await will make promises obsolete

Don’t. With Async/Await, we are still using promises. There were even some use cases Async/Await that didn’t cut it and we had to go back to Promises for help. One such scenario is when we need to make multiple independent asynchronous calls and wait for all of them to complete.

If we try to do this with async and await, the following happens:


async function getABC() {
  letA = await getValueA(); // getValueA takes 2 seconds to completeletB = await getValueB(); // etValueB takes 4 seconds to completeletC = await getValueC(); // getValueC takes 3 seconds to completereturn A*B*C;
}Copy the code

Each wait call will wait for the previous return result. Since we only make one call at a time, the entire function takes 9 seconds from start to finish (2 + 4 + 3).

This is not an optimal solution because of these three variables
A.
BAs well as
CNot dependent on each other. In other words, we don’t need to know
APrevious value
B. We can get them at the same time and wait a few seconds. To send all requests at the same time,
Promise.all()You need to. This will ensure that we still have all the results before continuing, but the asynchronous calls will fire in parallel rather than one after another.

async function getABC() {// promise.all () allows all requests to be sent at the same time.let results = await Promise.all([ getValueA, getValueB, getValueC ]); 
  return results.reduce((total,value) => total * value);
}Copy the code

This way, the feature will take less time. The GetValueA and GetValueC calls will complete on GetValueB. We will effectively reduce the execution time to the time of the slowest request (getValueB-4 seconds), rather than the sum of The Times.

Handle errors in Async/Await

Another benefit of Async/Await is that it allows us to catch any unexpected errors in a good old try/catch block.
We just need to
awaitWrap our call like this:

async function doSomethingAsync(){try {// This asynchronous call may fail.letresult = await someAsyncCall(); } catch(error) {// If this fails, the error will be caught here}}Copy the code

The catch clause will handle errors raised by waiting asynchronous calls or any other failed code we might write inside the try block.

We can also catch errors when executing asynchronous functions if the situation requires it. Because all asynchronous functions return promises, we can simply include a.catch () event handler when calling them.

// Async with no try/catch blockfunction doSomethingAsync(){// This asynchronous call may faillet result = await someAsyncCall();
    returnresult; } // Catch an error when calling this function.doSomethingAsync().
    .then(successHandler)
    .catch(errorHandler);Copy the code

It is important to choose your preferred error handling method and stick to it. Using try/catch and.catch () together is likely to cause problems.

Browser support

Async/Await is already available in most major browsers. This only excludes IE11 – all other vendors will recognize your asynchronous/wait code without the need for external libraries.



Asynchronous/wait browser support


Reference: tutorialzine.com/2017/07/jav…