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