Firebase 如何避免承诺嵌套

Firebase 如何避免承诺嵌套,firebase,google-cloud-functions,Firebase,Google Cloud Functions,我有一种感觉,我在下面的简单函数中进行了过度嵌套,它只是从一个位置读取一个值并将其写入另一个位置 有没有办法简化它 exports.myFunc = functions.database.ref('...').onCreate(event => { const list_id = event.params.list_id; return new Promise(function(resolve, reject){ event.data.adminRef.ro

我有一种感觉,我在下面的简单函数中进行了过度嵌套,它只是从一个位置读取一个值并将其写入另一个位置

有没有办法简化它

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

如果你已经有了承诺,你就不需要新的承诺。您可以从
返回承诺,然后
继续链接

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

如果你已经有了承诺,你就不需要新的承诺。您可以从
返回承诺,然后
继续链接

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

为什么要使用
returnpromise.reject('error message')
而不是
reject()?由于外部承诺函数已不存在,因此我不再调用拒绝方法。我必须向传递给then()的函数返回一个承诺才能将其传播。为什么要使用
return promise.reject('error message')
而不是
reject()?由于外部承诺函数已不存在,因此我不再调用拒绝方法。我必须向传递给then()的函数返回一个承诺,以将其向上传播。