Wednesday, 19 April 2017

Promise.all() Alternative that allows failure?

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.

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 ?

Is there a Promise method or module i'm supposed to use ?

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;
    })
};



via Sanket Berde

No comments:

Post a Comment