TL; DR
Use Promise.allpara chamadas de função paralelas, o comportamento da resposta não está correto quando o erro ocorre.
Primeiro, execute todas as chamadas assíncronas de uma só vez e obtenha todos os Promiseobjetos. Segundo, use awaitnos Promiseobjetos. Dessa forma, enquanto você espera pela primeira Promisesolução, as outras chamadas assíncronas ainda estão em andamento. No geral, você só esperará enquanto a chamada assíncrona mais lenta. Por exemplo:
// Begin first call and store promise without waiting
const someResult = someCall();
// Begin second call and store promise without waiting
const anotherResult = anotherCall();
// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];
// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise
Exemplo de JSbin: http://jsbin.com/xerifanima/edit?js,console
Advertência: não importa se as awaitchamadas estão na mesma linha ou em linhas diferentes, desde que a primeira awaitchamada ocorra após todas as chamadas assíncronas. Veja o comentário de JohnnyHK.
Atualização: esta resposta tem um tempo diferente no tratamento de erros, de acordo com a resposta do @ bergi , NÃO lança o erro à medida que o erro ocorre, mas depois que todas as promessas são executadas. Comparo o resultado com a dica de @ jonny:, [result1, result2] = Promise.all([async1(), async2()])verifique o seguinte snippet de código
const correctAsync500ms = () => {
return new Promise(resolve => {
setTimeout(resolve, 500, 'correct500msResult');
});
};
const correctAsync100ms = () => {
return new Promise(resolve => {
setTimeout(resolve, 100, 'correct100msResult');
});
};
const rejectAsync100ms = () => {
return new Promise((resolve, reject) => {
setTimeout(reject, 100, 'reject100msError');
});
};
const asyncInArray = async (fun1, fun2) => {
const label = 'test async functions in array';
try {
console.time(label);
const p1 = fun1();
const p2 = fun2();
const result = [await p1, await p2];
console.timeEnd(label);
} catch (e) {
console.error('error is', e);
console.timeEnd(label);
}
};
const asyncInPromiseAll = async (fun1, fun2) => {
const label = 'test async functions with Promise.all';
try {
console.time(label);
let [value1, value2] = await Promise.all([fun1(), fun2()]);
console.timeEnd(label);
} catch (e) {
console.error('error is', e);
console.timeEnd(label);
}
};
(async () => {
console.group('async functions without error');
console.log('async functions without error: start')
await asyncInArray(correctAsync500ms, correctAsync100ms);
await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);
console.groupEnd();
console.group('async functions with error');
console.log('async functions with error: start')
await asyncInArray(correctAsync500ms, rejectAsync100ms);
await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);
console.groupEnd();
})();