Promise.all() 允许失败的替代方案? [英] Promise.all() Alternative that allows failure?
问题描述
据我了解,Promise.all() 并行执行所有内容,并在任一 Promise 中的第一个错误实例返回错误.
As i understand it, Promise.all() executes everything in parallel and returns a error at the first instance of error in either of the Promises.
现在,如果我想并行运行所有 Promise 并等待它们完成,即使其中一个失败了怎么办?
Now what if i want to run all promises in parallel and wait for them to complete even if one of them were to fail ?
是否有我应该使用的 Promise 方法或模块?
Is there a Promise method or module i'm supposed to use ?
我正在并行发送一堆用户 FCM 推送通知,并且如果其中任何一个失败,则 .then() 排队失败.
Im sending a bunch of users FCM push notifications in parallel and Failing the .then() queueing if any one of them fails is not intended.
我在我的代码中这样做
//then chain
.then(()=>{
let startChatPromises = [];
for (let i = 0 ; i < queue_length ; i ++){
startChatPromises.push(matchUsers(some_key,some_key));
}
return Promise.all(startChatPromises);
}).then(()=>{// Continue processing even after failure ?});
let matchUsers = (room_id,...user_ids) => {
let chat_key = admin.database().ref().child("chats").child(room_id).push().key;
let participants = {};
user_ids.forEach(user_id=> {
participants[`${user_id}`] = true;
});
return admin.database().ref().child("chats").child(room_id).child(chat_key).update({
"last_message_ts" : new Date().getTime(),
"participants" : participants
}).then(()=>{
//Get Users
let getFCMTokenPromises = [];
user_ids.forEach(user_id => {
getFCMTokenPromises.push(admin.database().ref("users").child(user_id).child("fcm_id").once('value'));
});
return Promise.all(getFCMTokenPromises);
}).then(results => {
// Send Push Notifications
let tokens = [];
results.forEach(snapshot=>{
if (snapshot.val() !== undefined && snapshot.val() !== null && snapshot.val() !== "")
tokens.push(snapshot.val());
});
const payload = {
data: {
NOTIFICATION_TYPE: 'START_CHAT',
CHAT_UID: chat_key
}
};
return admin.messaging().sendToDevice(tokens, payload);
}).catch(()=>{
return true;
})
};
推荐答案
你可以这样做:
function allSkippingErrors(promises) {
return Promise.all(
promises.map(p => p.catch(error => null))
)
}
这会将所有有错误的 Promise
对象解析为结果数组中的 null
.您还可以使用 .catch(error => error)
保留 Error
对象,以在最后检测故障,或解析为具有 { 状态的对象, 结果, 错误 }
属性.
This will resolve all the Promise
objects with errors to a null
in the resulting array. You could also keep the Error
object using .catch(error => error)
, to detect failures at the end, or resolve to an object with { status, result, error }
properties.
这篇关于Promise.all() 允许失败的替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!