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 evaluates as 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.

Note that while the async function is paused, the calling function continues running (having received the implicit Promise returned by the async function).

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("slow");
      console.log("slow promise is done");
    }, 2000);
  });
};

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

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

  // 1. Execution gets here almost instantly
  const slow = await resolveAfter2Seconds();
  console.log(slow); // 2. this runs 2 seconds after 1.

  const fast = await resolveAfter1Second();
  console.log(fast); // 3. this runs 3 seconds after 1.
}

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

  // 1. Execution gets here almost instantly
  console.log(await slow); // 2. this runs 2 seconds after 1.
  console.log(await fast); // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved
}

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

var parallel = async function() {
  console.log('==PARALLEL with await Promise.all==');
  
  // Start 2 "jobs" in parallel and wait for both of them to complete
  await Promise.all([
      (async()=>console.log(await resolveAfter2Seconds()))(),
      (async()=>console.log(await resolveAfter1Second()))()
  ]);
}

// This function does not handle errors. See warning below!
var parallelPromise = 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(concurrentPromise, 7000); // same as concurrentStart

// wait again
setTimeout(parallel, 10000); // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow"

// wait again
setTimeout(parallelPromise, 13000); // same as parallel

await and parallelism

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. The code finishes after 3 seconds.

In concurrentStart, both timers are created and then awaited. The timers are running concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer.
However the await calls are still running in series, which means the second await will wait for the first one to finish. In this case, this leads to the processing of the result of the fastest timer to be performed after the slowest.

If you wish to fully perform two or more jobs in parallel, you must use await Promise.all([job1(), job2()]) as shown in the parallel example.

async/await vs Promise#then and error handling

Most async functions can also be written as regular functions using Promises. However async functions are a little bit less error-prone when it comes to error handling.

Both concurrentStart and concurrentPromise are functionally equivalent.
In concurrentStart, if either of the awaited calls fail, the exception will be automatically caught, the async function execution interrupted, and the Error propagated to the caller through the implicit return Promise.
For the same to happen in the Promise case, the function must take care of returning a Promise which captures the completion of the function. In concurrentPromise that means returning the promise from Promise.all([]).then(). As a matter of fact, a previous version of this example forgot to do this!

It is however still possible for async functions to mistakenly swallow errors.
Take for example the parallel async function. If it didn't await (or return) the result of the Promise.all([]) call, any Error would not have been propagated.
While the parallelPromise example seem simple, it does not handle errors at all! Doing so would require a similar return Promise.all([]).

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.

return await promiseValue; vs. return promiseValue;

The implicit wrapping of return values in Promise.resolve does not imply that return await promiseValue; is functionally equivalent to return promiseValue;

Consider the following rewrite of the above code that returns null if processDataInWorker were to reject with an error:

async function getProcessedData(url) {
  let v;
  try {
    v = await downloadData(url);
  } catch(e) {
    v = await downloadFallbackData(url);
  }
  try {
    return await processDataInWorker(v); // Note the `return await` vs. just `return`
  } catch (e) {
    return null;
  }
}

Having simply written return processDataInWorker(v); would have caused the Promise returned by the function to reject instead of resolving to null in the case where processDataInWorker(v) rejects. This highlights the subtle difference between return foo; and return await foo; which is that return foo; will immediately return foo and never throw even if foo is a promise and rejects whereas return await foo; will wait for foo to resolve or reject if it's a promise and will throw before returning if it rejects.

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 AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
async functionChrome 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 55Firefox 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

ডকুমেন্ট ট্যাগ এবং অবদানকারী

ট্যাগ: 
সর্বশেষ হালনাগাদ করেছেন: jochem,