JavaScript Async


Using async and await makes it simpler to write promises.

The use of async in a function causes it to return a Promise.

The await keyword causes a function to pause and wait for a Promise.

Async Syntax

When you use the keyword async before a function, it causes the function to return a promise.

Example

async function myFunction() {
  return "Hello";
}

Is the same as:

function myFunction() {
  return Promise.resolve("Hello");
}

Here's how you can utilize the Promise:

myFunction().then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

Or in simpler terms, when you anticipate receiving a regular value (a standard response, not an error):


Await Syntax

The await keyword is only allowed within a function that has been declared as async.

The await keyword causes the function to stop running temporarily and wait until a promise is fulfilled before it resumes execution:

let value = await promise;

Example

Take it step by step and understand how to utilize it.

JavaScript already has two pre-defined terms: "resolve" and "reject."

We won't make them ourselves, but summon one when the executor function is prepared.

Frequently, we won't require a reject function.