首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

async function

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

您还可以使用异步函数语句来定义异步函数。

语法

代码语言:javascript
复制
async function [name]([param1[, param2[, ..., paramN]]]) {
   statements
}

从ES2015开始,您也可以使用箭头功能。

参数

name此异步函数的名称,可省略。如果省略则这个函数将成为匿名函数。该名称仅可在本函数中使用。

paramN传入函数的形参名称。

statements组成函数体的语句。

描述

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

示例

简单示例

代码语言:javascript
复制
function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
};


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

add(10).then(v => {
  console.log(v);  // prints 60 after 4 seconds.
});


(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);  // prints 60 after 2 seconds.
});

规范

Specification

Status

Comment

ECMAScript Latest Draft (ECMA-262)The definition of 'async function' in that specification.

Living Standard

Initial definition in ES2017.

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari (WebKit)

Basic support

55

?

52.0 (52.0)

?

42

?

Feature

Android

Android Webview

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Chrome for Android

Basic support

?

?

?

52.0 (52.0)

?

42

?

55

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com