如何避免嵌套承诺? [英] How to avoid nested promises?

查看:54
本文介绍了如何避免嵌套承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写 firebase 函数,我想知道是否有任何方法可以避免此 JavaScript 代码中的嵌套承诺?

I'm trying to write firebase function and I wonder if is any way to avoid nested promises in this JavaScript code?

exports.sendNotification=functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change,context)=>{

const userId=context.params.user_id;
const notificationId=context.params.notification_id;

console.log('We have a notification to send to: ', userId);

if(!change.after.val()){
    return console.log('A notification has been deleted from database ',notificationId);
}
const fromUser=change.after.ref.root.child("/notifications/"+userId+"/"+notificationId).once('value');
return fromUser.then(fromUserResult=>{
    const fromUserID=fromUserResult.val().from;
    console.log('You have new notification from'+fromUserID);

    const userQuery=change.after.ref.root.child(`users/${fromUserID}/name`).once('value');
    const deviceToken=change.after.ref.root.child("/users/"+userId+"/device_token").once('value');

    return Promise.all([userQuery, deviceToken]).then(resut=>{

        const userName=resut[0].val();
        const token_id=resut[1].val();

        const payload={
            notification:{
                title: "Friend request",
                body: `${userName} has send you request`,
                icon: "default",
                click_action: "com.mwdevp.android.lapitchat_TARGET_NOTIFICATION"
            },
            data :{
                USER_KEY: fromUserID
            }
        };

        return admin.messaging().sendToDevice(token_id,payload).then(response=>{
        console.log('This was the notification feature');
        return;
        });

    });
});
});

有人知道如何避免这段代码中的嵌套承诺吗?

Does somebody any idea how can I avoid nested promises in this code?

推荐答案

将嵌套的 then 调用移动到外部 promise 链,并在下一个 then 中传递你需要的变量code> 回调作为 Promise.all 调用中的额外值:

Move the nested then calls to the outer promise chain, and pass the variables you need in a next then callback as extra value in the Promise.all call:

return fromUser.then(fromUserResult=>{
    const fromUserID=fromUserResult.val().from;
    console.log('You have new notification from'+fromUserID);

    const userQuery=change.after.ref.root.child(`users/${fromUserID}/name`).once('value');
    const deviceToken=change.after.ref.root.child("/users/"+userId+"/device_token").once('value');

    return Promise.all([userQuery, deviceToken, fromUserID]); // <--- add third value
}).then(resut=>{
    const userName=resut[0].val();
    const token_id=resut[1].val();

    const payload={
        notification:{
            title: "Friend request",
            body: `${userName} has send you request`,
            icon: "default",
            click_action: "com.mwdevp.android.lapitchat_TARGET_NOTIFICATION"
        },
        data :{
            USER_KEY: resut[2]; // <----
        }
    };

    return admin.messaging().sendToDevice(token_id,payload);
}).then(response=>{
    console.log('This was the notification feature');
    return;
});

这篇关于如何避免嵌套承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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