Async Await

I. What is Async-Await?

Async/Await is another way to handle asynchronous tasks.

To use it, we must declare the function with the async keyword. Then inside the function, you can use await.

Example: We want to fetch data from an API using the axios library.

We have to wait for a response from the server, which is an asynchronous HTTP request.

Below we will write the same function in 2 different ways. 1st way with Promises, and 2nd way with Async / Await

// Using Promise:
function getData() {
  return new Promise(function(resolve) {
    axios.get("https://api.com/example.json").then(function (json) {
      resolve(json);
    });
  });
}

// Using Async/Await
async function getDataAsync() {
  let json = await axios.get("https://api.com/example.json");
  return json;
}

II. async keyword

The async keyword is used to declare an asynchronous function.

Syntax

async function myFunc() {
  // Function
}

myFunc();

We can also create async function expressions:

const myFunc = async () => {
  // Function
};

myFunc();

async functions always return a promise, so we can use traditional promise syntax, like .then() and .catch

async function fivePromise() {
  return 5;
}

fivePromise().then((resolvedValue) => {
  console.log(resolvedValue);
}); // Prints 5

III. await Operator

await is an operator used only inside an async function and halts the execution of a function until a given promise is no longer pending.

The await keyword waits until that promise settles, and then:

  • Returns the result
  • If it’s an error, the exception is generated.
async function f() {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000);
  });

  let result = await promise; // wait until the promise resolves (*)

  alert(result); // "done!"
}

f();

If a promise resolves normally, then await promise returns the result. However, in the case of a rejection, it throws the error.

async function f() {
  await Promise.reject(new Error("Whoops!"));
}

is the same as:

async function f() {
  throw new Error("Whoops!");
}

IV. Handling errors

With async…await, we use try…catch statements for error handling.

async function usingTryCatch() {
  try {
    let resolveValue = await asyncFunction("thing that will fail");
    let secondValue = await secondAsyncFunction(resolveValue);
  } catch (err) {
    // Catches any errors in the try block
    console.log(err);
  }
}

usingTryCatch();

V. Async/Await and Promise.all()

We can use Async/Await with Promise.all()

async function asyncPromAll() {
  const resultArray = await Promise.all([
    asyncTask1(),
    asyncTask2(),
    asyncTask3(),
    asyncTask4(),
  ]);
  for (let i = 0; i < resultArray.length; i++) {
    console.log(resultArray[i]);
  }
}