将回调转换为promise的正确方法是什么

时间:2017-12-10 21:24:14

标签: javascript node.js google-cloud-functions

我是Node的新手,我正在使用它编写一些Firebase云函数来调用外部API。我正在与承诺斗争。我知道如何使用回调,但我无法弄清楚如何将回调转换为promise。我想在newJobRequestSubmitted方法中使用promises,所以我没有嵌套的回调。我也希望它能解决我在达到最终return语句之前函数完成的问题。以下是调用方法的方法和实现......

更新:

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

};

1 个答案:

答案 0 :(得分:0)

正如Bergi已经评论过的那样,请使用可用的承诺。

但是,因为节点8有一个promisify:

或者使用蓝鸟: