TL; DR
Utilizzare Promise.allper le chiamate di funzione parallele, la risposta si comporta in modo non corretto quando si verifica l'errore.
Innanzitutto, esegui tutte le chiamate asincrone contemporaneamente e ottieni tutti gli Promiseoggetti. In secondo luogo, utilizzare awaitsugli Promiseoggetti. In questo modo, mentre aspetti che il primo si Promiserisolva, le altre chiamate asincrone procedono ancora. Complessivamente, attenderai fino a quando la chiamata asincrona più lenta. Per esempio:
// 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
Esempio di JSbin: http://jsbin.com/xerifanima/edit?js,console
Avvertenza: non importa se le awaitchiamate si trovano sulla stessa linea o su linee diverse, a condizione che la prima awaitchiamata avvenga dopo tutte le chiamate asincrone. Vedi il commento di JohnnyHK.
Aggiornamento: questa risposta ha una diversa tempistica nella gestione degli errori in base alla risposta di @ bergi , NON genera l'errore man mano che si verifica l'errore ma dopo che tutte le promesse sono state eseguite. Confronto il risultato con il suggerimento di @ jonny:, [result1, result2] = Promise.all([async1(), async2()])controlla il seguente frammento di codice
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();
})();