Ви читаєте англійську версію цього вмісту, бо ще не існує перекладу для цієї мови. Допоможіть нам перекласти цю статтю!
Оператор await
використовується для очікування Promise
. Він може бути використаний лише в середині async function
.
Синтаксис
[rv] = await expression;
expression
- A
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
.
Опис
The await
expression causes async
function execution to pause until a Promise
is fulfilled, that is resolved 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
.
If the 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.
Приклади
If a 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();
If the value is not a Promise
, it converts the value to a resolved Promise
, and waits for it.
async function f2() { var y = await 20; console.log(y); // 20 } f2();
If the Promise
is rejected, the rejected value is thrown.
async function f3() { try { var z = await Promise.reject(30); } catch(e) { console.log(e); // 30 } } f3();
Handle rejected Promise
without try block.
var response = await promisedFunction().catch((err) => { console.log(err); }); // response will be undefined if the promise is rejected
Специфікації
Специфікація | Статус | Коментар |
---|---|---|
ECMAScript Latest Draft (ECMA-262) The definition of 'async functions' in that specification. |
Draft | Initial definition in ES2017. |
Підтримка веб-переглядачами
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
await | Chrome Full support 55 | Edge Full support 14 | 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 | Firefox Android Full support 52 | Opera Android Full support 42 | Safari iOS Full support 10.3 | Samsung Internet Android Full support 6.0 | nodejs
Full support
7.6.0
|
Legend
- Full support
- Full support
- No support
- No support
- User must explicitly enable this feature.
- User must explicitly enable this feature.