async function 关键字用来在表达式中定义异步函数。当然,你也可以用 异步函数语句 来定义。

语法

async function [name]([param1[, param2[, ..., paramN]]]) { statements }

参数

name
此异步函数的名称,可省略。如果省略则这个函数将成为匿名函数。该名称仅可在本函数中使用。
paramN
传入函数的形参名称。
statements
组成函数体的语句。

描述

异步函数表达式与 异步函数语句 非常相似,语法也基本相同。它们之间的主要区别在于异步函数表达式可以省略函数名称来创建一个匿名函数。另外,异步函数表达式还可以用在 IIFE (立即执行函数表达式,Immediately Invoked Function Expression) 中,更多信息见 函数

示例

一个简单例子

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
};

// async function expression assigned to a variable
var add1 = async function(x) {
  var a = await resolveAfter2Seconds(20);
  var b = await resolveAfter2Seconds(30);
  return x + a + b;
}

add1(10).then(v => {
  console.log(v);  // 4 秒后打印 60
});

(async function(x) { // async function expression used as an IIFE
  var p_a = resolveAfter2Seconds(20);
  var p_b = resolveAfter2Seconds(30);
  return x + await p_a + await p_b;
})(10).then(v => {
  console.log(v);  // 2 秒后打印 60
});

规范

Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
async function
Draft ES2017 中的初始定义

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support 55Edge ? Firefox Full support 52IE No support NoOpera Full support 42Safari Full support 10.1WebView Android Full support 55Chrome Android Full support 55Edge Mobile ? Firefox 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
Compatibility unknown  
Compatibility unknown
User must explicitly enable this feature.
User must explicitly enable this feature.

相关链接

文档标签和贡献者

此页面的贡献者: Terry.Qiao, fphonor, xgqfrms-GitHub, x-cold, Rusion-Wayne
最后编辑者: Terry.Qiao,