如何避免承诺嵌套 [英] How to avoid promise nesting

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

问题描述

我有一种感觉,我正在使用以下简单函数嵌套过度杀毒,该函数只是从一个位置读取一个值并将其写入另一个位置.

I have a feeling I'm doing an overkill nesting in the following simple function, which simply reads a value from one location and writes it to another location.

有某种方法可以简化它吗?

Is there a way to simplify it somehow?

exports.myFunc = functions.database.ref('...').onCreate(event => {
    const list_id = event.params.list_id;
    return new Promise(function(resolve, reject){
        event.data.adminRef.root.child('lists').child(list_id).child('owner').once('value').then(function(snap){
            const owner_id = snap.val();
            if (owner_id != null) {
                event.data.adminRef.root.child('users').child(owner_id).child('whatever').child('whatever2').set(true)
                    .then(function() {
                        resolve();
                    },
                    function(err) {
                        reject();
                    }
                )
            } else {
                reject();
            }
        });
    });
})

推荐答案

如果现有的承诺可以使用,则不需要新的承诺.您可以从then返回诺言以继续链接.

You don't need a new promise if you have existing promises to work with. You can return promises from then to continue chaining.

exports.myFunc = functions.database.ref('...').onCreate(event => {
    const list_id = event.params.list_id;
    return event.data.adminRef.root.child('...').once('value')
    .then(function(snap){
        const owner_id = snap.val();
        if (owner_id != null) {
            return event.data.adminRef.root.child('...').set(true)
        } else {
            return Promise.reject('error message')
        }
    });
})

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

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