TL; DR
Promise.allParalel işlev çağrıları için kullanın , hata oluştuğunda yanıt davranışları doğru değil.
İlk olarak, tüm eşzamansız çağrıları bir kerede yürütün ve tüm Promisenesneleri alın. İkincisi, nesneler awaitüzerinde kullanın Promise. Bu şekilde, Promisediğer asenkron çağrıları çözümlemek için ilk beklerken hala devam ediyor. Genel olarak, yalnızca en yavaş eşzamansız çağrı kadar bekleyeceksiniz. Örneğin:
// 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
JSbin örneği: http://jsbin.com/xerifanima/edit?js,console
Uyarı:await İlk awaitçağrı , tüm eşzamansız çağrılardan sonra gerçekleştiği sürece , çağrıların aynı hatta veya farklı hatlarda olması önemli değildir . JohnnyHK'nın yorumuna bakın.
Güncelleme: Bu yanıt göre hata işleme farklı bir zamanlaması vardır @ Bergi cevabı , bu mu DEĞİL tüm sözler yürütülür sonra hata oluşur olarak hatayı dışarı atmak ama. Sonucu @ jonny'nin ipucuyla karşılaştırırım: [result1, result2] = Promise.all([async1(), async2()])Aşağıdaki kod snippet'ini kontrol et
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();
})();