async function
키워드는 async
함수를 정의하는데 사용되는 표현식이다.
Syntax
async function [name]([param1[, param2[, ..., paramN]]]) { statements }
Parameters
name
- 함수 이름. 함수의 이름은 오직 함수 몸체에서 지역적으로 사용되며, 함수 이름을 선언하지 않으면 익명함수로 사용된다.
paramN
- 함수에 전달되는 매개변수.
statements
- 함수 몸체를 구성하는 '문'.
Description
async function
표현식은 async function statement
문법과 매우 비슷하다. async function
표현식과 async function
문의 주된 차이는 익명함수로써의 사용 여부인데, async function 표현식은 함수 이름이 없으면 익명함수를 만든다. async function 표현식은 익명함수로 사용될 수 있기 때문에 IIFE (즉시실행함수)로 사용될 수 있다. 더 자세한 정보는 functions
챕터를 참고하라.
Examples
Simple example
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
};
(async function(x) { // 즉시실행함수로 사용된 async function
.
var a = resolveAfter2Seconds(20);
var b = resolveAfter2Seconds(30);
return x + await a + await b;
})(10).then(v => {
console.log(v); // 2초 후에 콘솔에 60을 찍는다.
});
var add = async function(x) { // 변수에 할당된 async function 표현식.
var a = await resolveAfter2Seconds(20);
var b = await resolveAfter2Seconds(30);
return x + a + b;
};
add(10).then(v => {
console.log(v); // 4초 후에 콘솔에 60을 찍는다.
});
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2017 Draft (ECMA-262) The definition of 'async function' 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 | ? |
Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|
Basic support | ? | ? | 52.0 (52.0) | ? | 42 | ? | 55 |
See also
async function
AsyncFunction
objectawait