Promise.all()允许失败的替代方法? [英] Promise.all() Alternative that allows failure?

查看:125
本文介绍了Promise.all()允许失败的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Promise.all()并行执行所有操作,并在两个Promises中的第一个错误实例处返回错误。

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.

我正在用我的代码这样做

I'm Doing this in my code

//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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆