Deklaracja funkcji async
definiuje funkcję asynchroniczną, która zwraca obiekt AsyncFunction
. Funkcja asynchroniczna to funkcja, która działa asynchroniczne poprzez zdarzenie pętli używając bezwarunkowego Promise
do zwrócenia wyniku. Składnia i struktura kodu używanego przy funkcjach asynchronicznych jest jednakże bardziej podobna do znanych ze standardowych funkcji synchronicznych.
Możesz zdefiniować funkcje asynchroniczne również poprzez użycie async function expression.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Źródło niniejszego interaktywnego demo znajduje się na repozytorium GitHuba. Jeśli chcesz mieć wkład w ten interaktywny projekt demo po prostu sklonuj https://github.com/mdn/interactive-examples i wyślij nam żądanie pull.
Składnia
async function name([param[, param[, ... param]]]) { statements }
Parametry
name
- Nazwa funkcji.
param
- Nazwa argumentu, który zostanie podany do funkcji.
statements
- Wyrażenia stanowiące ciało funkcji.
Wartość zwrotna (return)
Promise
, które zostanie rozwiązane z wartością zwróconą przez funkcję asynchroniczną lub odrzucone z nieprzechwyconym wyjątkiem wyrzuconym z funkcji asynchronicznej.
Opis
Funkcja async
może zawierać wyrażenie await
, które wstrzymuje wywołanie funkcji asynchronicznej i czeka na przekazaną deklarację Promise
i wtedy wznawia wywołanie funkcji async
oraz interpretuje jako wartość rozwiązaną.
Pamiętaj, że polecenie await
działa wyłącznie wewnątrz funkcji async
. Jeśli użyjesz go poza ciałem funkcji async
otrzymasz SyntaxError
.
Zauważ, że kiedy funkcja async
jest wstrzymana, funkcja wywołująca kontynuuje działanie (otrzymując domyślny Promise zwracany przez funkcję async
).
Celem funkcji async
/await
jest uproszczenie działania używając obietnic (promises) synchronicznie oraz by wykonać pewne działania w grupie Promises
. Tak, jak Promises
są podobne do strukturalnych callbacków, tak async
/await
jest podobne do kombinacji generatorów i obietnic.
Przykłady
Prosty przykład
var resolveAfter2Seconds = function() {
console.log("starting slow promise");
return new Promise(resolve => {
setTimeout(function() {
resolve("slow");
console.log("wolna obietnica została wykonana");
}, 2000);
});
};
var resolveAfter1Second = function() {
console.log("starting fast promise");
return new Promise(resolve => {
setTimeout(function() {
resolve("fast");
console.log("szybka obietnica została wykonana");
}, 1000);
});
};
var sequentialStart = async function() {
console.log('==START SEKWENCYJNY==');
// 1. Niemalże natychmiast dochodzi do wywołania
const slow = await resolveAfter2Seconds();
console.log(slow); // 2. to zostaje wywołanie 2s po 1.
const fast = await resolveAfter1Second();
console.log(fast); // 3. to zostaje wykonane 3s po 1.
}
var concurrentStart = async function() {
console.log('==RÓWNOCZESNY START z await==');
const slow = resolveAfter2Seconds(); // licznik startuje od razu
const fast = resolveAfter1Second(); // licznik startuje od razu
// 1. Niemalże natychmiast dochodzi do wywołania
console.log(await slow); // 2. jest wywołane 2s po 1.
console.log(await fast); // 3. jest wywołane 2s po 1., natychmiast po 2., podczas gdy szybka jest już wykonana
}
var concurrentPromise = function() {
console.log('==RÓWNOCZESNY START z Promise.all==');
return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
console.log(messages[0]); // wolne
console.log(messages[1]); // szybkie
});
}
var parallel = async function() {
console.log('==RÓWNOLEGLE z await Promise.all==');
// Równolegle startują dwa zadania i czekamy na zakończenie działania obu
await Promise.all([
(async()=>console.log(await resolveAfter2Seconds()))(),
(async()=>console.log(await resolveAfter1Second()))()
]);
}
// This function does not handle errors. See warning below!
var parallelPromise = function() {
console.log('==PARALLEL with Promise.then==');
resolveAfter2Seconds().then((message)=>console.log(message));
resolveAfter1Second().then((message)=>console.log(message));
}
sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
// wait above to finish
setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
// wait again
setTimeout(concurrentPromise, 7000); // same as concurrentStart
// wait again
setTimeout(parallel, 10000); // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow"
// wait again
setTimeout(parallelPromise, 13000); // same as parallel
await
and parallelism
In sequentialStart
, execution suspends 2 seconds for the first await
, and then again another 1 second for the second await
. The second timer is not created until the first has already fired. The code finishes after 3 seconds.
In concurrentStart
, both timers are created and then await
ed. The timers are running concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer.
However the await
calls are still running in series, which means the second await
will wait for the first one to finish. In this case, this leads to the processing of the result of the fastest timer to be performed after the slowest.
If you wish to fully perform two or more jobs in parallel, you must use await Promise.all([job1(), job2()])
as shown in the parallel
example.
async
/await
vs Promise#then and error handling
Most async functions can also be written as regular functions using Promises. However async
functions are a little bit less error-prone when it comes to error handling.
Both concurrentStart
and concurrentPromise
are functionally equivalent.
In concurrentStart
, if either of the await
ed calls fail, the exception will be automatically caught, the async function execution interrupted, and the Error propagated to the caller through the implicit return Promise.
For the same to happen in the Promise case, the function must take care of returning a Promise
which captures the completion of the function. In concurrentPromise
that means return
ing the promise from Promise.all([]).then()
. As a matter of fact, a previous version of this example forgot to do this!
It is however still possible for async
functions to mistakenly swallow errors.
Take for example the parallel
async function. If it didn't await
(or return
) the result of the Promise.all([])
call, any Error would not have been propagated.
While the parallelPromise
example seem simple, it does not handle errors at all! Doing so would require a similar return
Promise.all([])
.
Rewriting a promise chain with an async
function
An API that returns a Promise
will result in a promise chain, and it splits the function into many parts. Consider the following code:
function getProcessedData(url) {
return downloadData(url) // returns a promise
.catch(e => {
return downloadFallbackData(url); // returns a promise
})
.then(v => {
return processDataInWorker(v); // returns a promise
});
}
it can be rewritten with a single async
function as follows:
async function getProcessedData(url) {
let v;
try {
v = await downloadData(url);
} catch(e) {
v = await downloadFallbackData(url);
}
return processDataInWorker(v);
}
Note that in the above example, there is no await
statement on the return
statement, because the return value of an async function
is implicitly wrapped in Promise.resolve
.
return await promiseValue;
vs. return promiseValue;
The implicit wrapping of return values in Promise.resolve
does not imply that return await promiseValue;
is functionally equivalent to return promiseValue;
Consider the following rewrite of the above code that returns null if processDataInWorker
were to reject with an error:
async function getProcessedData(url) {
let v;
try {
v = await downloadData(url);
} catch(e) {
v = await downloadFallbackData(url);
}
try {
return await processDataInWorker(v); // Note the `return await` vs. just `return`
} catch (e) {
return null;
}
}
Having simply written return processDataInWorker(v);
would have caused the Promise
returned by the function to reject instead of resolving to null
in the case where processDataInWorker(v)
rejects. This highlights the subtle difference between return foo;
and return await foo;
which is that return foo;
will immediately return foo
and never throw even if foo
is a promise and rejects whereas return await foo;
will wait for foo
to resolve or reject if it's a promise and will throw before returning if it rejects.
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript (ECMA-262) The definition of 'async function' in that specification. |
Living Standard | Initial definition in ES2017. |
ECMAScript 2017 (ECMA-262) The definition of 'async function' in that specification. |
Standard |
Browser compatibility
BCD tables only load in the browser