03. Await Expression
Если в асинхронной функции встречается выражение с ключевым словом await, значением которого является Promise, то она приостанавливает свою работу (как генератор) до тех пор, пока Promise не будет установлен:
If the Promise is fulfilled, the result of await is the fulfillment value.
If the Promise is rejected, await throws the rejection value.
Every await expression suspend execution. A function with multiple await expressions in it will be suspended once at a time on each await expression until that Promise is settled, before unsuspending execution and moving onto the next await expression
Handling a single asynchronous result
async function asyncFunc() {
const result = await otherAsyncFunc();
console.log(result);
}
// Equivalent to:
function asyncFunc() {
return otherAsyncFunc().then(result => {
console.log(result);
});
}Detach promise from await
Можно отделять вызов async операции от await результата на ней:
async function asyncFunc() {
const promise = otherAsyncFunc();
const result = await promise;
console.log(result);
}Handling multiple asynchronous results in parallel
Note that await is sequential, Promise.all() is parallel:
async function asyncFunc() {
const [result1, result2] = await Promise.all([
otherAsyncFunc1(),
otherAsyncFunc2(),
]);
console.log(result1, result2);
}
// Equivalent to:
function asyncFunc() {
return Promise.all([
otherAsyncFunc1(),
otherAsyncFunc2(),
])
.then([result1, result2] => {
console.log(result1, result2);
});
}Last updated
Was this helpful?