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 中的初始定义 |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
async function expression | Chrome Full support 55 | Edge Full support 15 | Firefox Full support 52 | IE No support No | Opera Full support 42 | Safari Full support 10.1 | WebView Android Full support 55 | Chrome Android Full support 55 | Edge Mobile Full support 15 | Firefox Android Full support 52 | Opera Android Full support 42 | Safari iOS Full support 10.1 | Samsung Internet Android Full support 6.0 | nodejs
Full support
7.6.0
|