Our volunteers haven't translated this article into हिन्दी (भारत) yet. Join us and help get the job done!
You can also read the article in English (US).

The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

You can also define async functions using an async function expression.

Syntax

async function name([param[, param[, ... param]]]) {
   statements
}

Parameters

name
The function name.
param
The name of an argument to be passed to the function.
statements
The statements comprising the body of the function.

Return value

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.

Description

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

Remember, the await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.

The purpose of async/await functions is to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises. Just as Promises are similar to structured callbacks, async/await is similar to combining generators and promises.

Examples

Simple example

var resolveAfter2Seconds = function() {
  console.log("starting slow promise");
  return new Promise(resolve => {
    setTimeout(function() {
      resolve(20);
      console.log("slow promise is done");
    }, 2000);
  });
};

var resolveAfter1Second = function() {
  console.log("starting fast promise");
  return new Promise(resolve => {
    setTimeout(function() {
      resolve(10);
      console.log("fast promise is done");
    }, 1000);
  });
};

var sequentialStart = async function() {
  console.log('==SEQUENTIAL START==');

  // If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
  const slow = await resolveAfter2Seconds();

  const fast = await resolveAfter1Second();
  console.log(slow);
  console.log(fast);
}

var concurrentStart = async function() {
  console.log('==CONCURRENT START with await==');
  const slow = resolveAfter2Seconds(); // starts timer immediately
  const fast = resolveAfter1Second();

  console.log(await slow);
  console.log(await fast); // waits for slow to finish, even though fast is already done!
}

var stillConcurrent = function() {
  console.log('==CONCURRENT START with Promise.all==');
  Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
    console.log(messages[0]); // slow
    console.log(messages[1]); // fast
  });
}

var parallel = function() {
  console.log('==PARALLEL with Promise.then==');
  resolveAfter2Seconds().then((message)=>console.log(message));
  resolveAfter1Second().then((message)=>console.log(message));
}

sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
// wait above to finish
setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
// wait again
setTimeout(stillConcurrent, 7000); // same as concurrentStart
// wait again
setTimeout(parallel, 10000); // trully parallel: after 1 second, logs "fast", then after 1 more second, "slow"

Do not confuse await for Promise#then

In sequentialStart, execution suspends 2 seconds for the first await, and then again another 1 second for the second await. The second timer is not created until the first has already fired.

In concurrentStart,  both timers are created and then awaited. The timers are running concurrently but the await calls are still running in series, meaning the second await will wait for the first one to finish. This leads the code to finish in 2 rather than 3 seconds, which is the time the slowest timer needs. The same happens in stillConcurrent using Promise.all this time.

If you wish to await two or more promises in parallel, you must still use Promise#then, as parallel does in the example.

Rewriting a promise chain with an async function

An API that returns a Promise will result in a promise chain, and it splits the function into many parts. Consider the following code:

function getProcessedData(url) {
  return downloadData(url) // returns a promise
    .catch(e => {
      return downloadFallbackData(url)  // returns a promise
    })
    .then(v => {
      return processDataInWorker(v); // returns a promise
    });
}

it can be rewritten with a single async function as follows:

async function getProcessedData(url) {
  let v;
  try {
    v = await downloadData(url); 
  } catch(e) {
    v = await downloadFallbackData(url);
  }
  return processDataInWorker(v);
}

Note that in the above example, there is no await statement on the return statement, because the return value of an async function is implicitly wrapped in Promise.resolve.

Specifications

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
The definition of 'async function' in that specification.
Draft Initial definition in ES2017.
ECMAScript 2017 (ECMA-262)
The definition of 'async function' in that specification.
Standard  

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support 55Edge Full support YesFirefox Full support 52IE No support NoOpera Full support 42Safari Full support 10.1WebView Android Full support YesChrome Android Full support 55Edge Mobile Full support YesFirefox Android Full support 52Opera Android Full support 42Safari iOS Full support 10.1Samsung Internet Android Full support 6.0nodejs Full support 7.6.0
Full support 7.6.0
Full support 7.0.0
Disabled
Disabled From version 7.0.0: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

See also

दस्तावेज़ टैग और योगदानकर्ता

अंतिम अद्यतन: CalebJay,