0

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

};
MikeG
  • 3,745
  • 1
  • 29
  • 51
  • 2
    Don't have `wiwAPICreateJobSite` take a `callback` parameter - just `return` that promise that `.post(…)` already gives you! – Bergi Dec 10 '17 at 21:31
  • I did as you suggested and updated the code above. But i can't figure out how to chain promises together so that they aren't nested like i have above... If you could show an example that would be much appreciated – MikeG Dec 11 '17 at 01:42
  • I don't see any problematic nesting in your code. You might want to avoid using `Promise.all` on a single-element-array, and you can [unnest](https://stackoverflow.com/a/22000931/1048572) the `.then(_ => true)` call, but the rest is really fine. – Bergi Dec 11 '17 at 11:17

1 Answers1

0

As Bergi already has commented, use the available promise.

But since Node 8 there is a promisify:

Or use bluebird:

Markus
  • 512
  • 1
  • 4
  • 21
  • While `promisify` is the correct answer to [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/1048572), I don't think it helps the OP here. – Bergi Dec 10 '17 at 21:51