简体   繁体   中英

What is the right way to convert callback to promise

I am fairly new to Node and I am using it to write some Firebase Cloud Functions that make calls to external APIs. I am struggling with promises. I know how to use callbacks but I can't figure out how to convert a callback into a promise. I want to make use of promises in newJobRequestSubmitted method so I don't have nested callbacks. I also hope it will solve the issue that I am having where the function finishes before the final return statement is reached. Here is the method and the implementations of the methods being called...

UPDATED:

exports.newJobRequestSubmitted = functions.database.ref('/job-requests').onWrite(event => { 

    if (event.data.val() === null) return null;

    const agilecrmContactRef = event.data.ref.root.child('contacts');


    return createWIWJobSite(jobSiteDescription, fullname, jobSiteAddress).then(jobsSiteResult => { 

        return Promise.all([
            createCRMDeal(agilecrmContactRef, type, numEmployees, startTime.getTime(), address, fullname, estimatedCost),       
            createWIWShift(notes, utcStartTime, utcEndTime, numEmployees, jobsSiteResult.site.id).then(result => {

                const userJobRequestsRef = event.data.adminRef.root.child('job-requests-by-user').child(userId).child(firebaseJobId);

                return Promise.all([
                    userJobRequestsRef.set({type: type, jobDate: jobDate, wheniworkJobId: result.shift.id, status: 'pending'}),         
                ]).then(_ => true);

            }).catch(err=> {

                return Promise.all([
                    event.data.ref.set(null)
                ]).then(_ => true);
            })

        ]).then(_ => true);

    }).catch(err=> { 
        console.log('ERROR  = ', err);
    });



});






var createCRMDeal = function(contactRef){

    const crm = new CRMManager(...);
    return agilecrmContactRef.once('value').then(snapshot=> {

        const deal = {
            ...
        };

        return crm.contactAPI.createDeal(deal, function(result) {
            console.log('succes creating deal = ', result);
        }, function(err){
            console.log('err creating deal = ', err);
        });

    });
};


var createWIWJobSite = function(){
    const wiw = new WIW(...);

    return wiw.post('sites', {
      "location_id": 3795651,
    });

};


var createWIWShift = function(jobSiteId){

    const wiw = new WIW(...);

    return wiw.post('shifts', {
      "site_id": jobSiteId,
    });

};

As Bergi already has commented, use the available promise.

But since Node 8 there is a promisify:

Or use bluebird:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM