Syntax
[rv] = await expression;
Description
await은 async함수의 실행을 중단시키고, Promise의 resolve값을 기다렸다가, resolve되면 다시 async함수를 실행시킨다. 만약 값이 Promise가 아니면 해당 값을 resolved Promise로 변환시킨다.
만약 Promise가 reject되면, await은 reject된 값을 throw한다.
Examples
만약 Promise가 await에 넘겨지면, await은 Promise가 resolve되길 기다렸다가, resolve되면 해당 값을 리턴한다.
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
만약 값이 Promise가 아니라면, 해당 값은 resolve된 Promise로 변환된다.
async function f2() {
var y = await 20;
console.log(y); // 20
}
f2();
만약 Promise가 reject되면, reject된 값이 throw된다.
async function f3() {
try {
var z = await Promise.reject(30);
} catch(e) {
console.log(e); // 30
}
}
f3();
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript Latest Draft (ECMA-262) The definition of 'async functions' in that specification. |
Draft | Initial definition in ES2017. |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Edge | Opera | Safari (WebKit) |
|---|---|---|---|---|---|---|
| Basic support | 55 | 52.0 (52.0) | ? | ? | 42 | 10.1 |
| Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|
| Basic support | No support | No support | 52.0 (52.0) | ? | 42 | 10.1 | 55 |