Slavik N
Slavik N

Reputation: 5328

How to avoid promise nesting

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

Upvotes: 0

Views: 889

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317928

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

Upvotes: 2

Related Questions