await
operator is used to wait for a
Promise
. It can only be used inside an
async function
.
[rv] = await expression;
expression
Promise
or any value to wait for.
rv
Returns the fulfilled value of the promise, or the value itself if it's not a
Promise
.
await
expression causes
async
function execution to pause until a
Promise
is settled (that is, fulfilled or rejected), and to resume execution of the
async
function after fulfillment. When resumed, the value of the
await
expression is that of the fulfilled
Promise
.
若
Promise
is rejected, the
await
expression throws the rejected value.
If the value of the
expression
following the
await
operator is not a
Promise
, it's converted to a
resolved Promise
.
An
await
can split execution flow, allowing the caller of the
await
's function to resume execution before the deferred continuation of the
await
's function. After the
await
defers the continuation of its function, if this is the first
await
executed by the function, immediate execution also continues by returning to the function's caller a pending
Promise
for the completion of the
await
's function and resuming execution of that caller.
若
Promise
is passed to an
await
expression, it waits for the
Promise
to be fulfilled and returns the fulfilled value.
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
Thenable objects
will be fulfilled just the same.
async function f2() {
const thenable = {
then: function(resolve, _reject) {
resolve('resolved!')
}
};
console.log(await thenable); // resolved!
}
f2();
If the value is not a
Promise
, it converts the value to a resolved
Promise
, and waits for it.
async function f3() {
var y = await 20;
console.log(y); // 20
}
f3();
若
Promise
is rejected, the rejected value is thrown.
async function f4() {
try {
var z = await Promise.reject(30);
} catch(e) {
console.error(e); // 30
}
}
f4();
Handle rejected
Promise
without try block.
var response = await promisedFunction().catch((err) => { console.error(err); });
// response will be undefined if the promise is rejected
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'async functions' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
await
|
Chrome 55 | Edge 14 | Firefox 52 | IE No | Opera 42 | Safari 10.1 | WebView Android 55 | Chrome Android 55 | Firefox Android 52 | Opera Android 42 | Safari iOS 10.3 | Samsung Internet Android 6.0 |
nodejs
7.6.0
|
完整支持
不支持
用户必须明确启用此特征。
async function
异步函数表达式
AsyncFunction
object