簡體   English   中英

什么是將回調轉換為Promise的正確方法

[英]What is the right way to convert callback to promise

我是Node的新手,並且使用它來編寫一些Firebase Cloud函數來調用外部API。 我在兌現諾言。 我知道如何使用回調,但是我不知道如何將回調轉換為Promise。 我想在newJobRequestSubmitted方法中使用newJobRequestSubmitted所以我沒有嵌套的回調。 我也希望它能解決我在到達最終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,
    });

};

正如Bergi所說,請使用可用的承諾。

但自從節點8開始,就有了一個承諾:

或使用藍鳥:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM