JavaScript参考手册
Operators
async function
async function
关键字用来在表达式中定义异步函数。当然,你也可以用 异步函数语句
来定义。
您还可以使用异步函数语句来定义异步函数。
语法
async function [name]([param1[, param2[, ..., paramN]]]) {
statements
}
从ES2015开始,您也可以使用箭头功能。
参数
name
此异步函数的名称,可省略。如果省略则这个函数将成为匿名函数。该名称仅可在本函数中使用。
paramN
传入函数的形参名称。
statements
组成函数体的语句。
描述
异步函数表达式与 异步函数语句
非常相似,语法也基本相同。它们之间的主要区别在于异步函数表达式可以省略函数名称来创建一个匿名函数。另外,异步函数表达式还可以用在 IIFE (立即执行函数表达式,Immediately Invoked Function Expression) 中,更多信息见 函数
。
示例
简单示例
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 |
Operators相关
JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络