[英]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. 我是Node的新手,并且使用它来编写一些Firebase Cloud函数来调用外部API。 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.
我知道如何使用回调,但是我不知道如何将回调转换为Promise。 I want to make use of promises in
newJobRequestSubmitted
method so I don't have nested callbacks. 我想在
newJobRequestSubmitted
方法中使用newJobRequestSubmitted
所以我没有嵌套的回调。 I also hope it will solve the issue that I am having where the function finishes before the final return statement is reached. 我也希望它能解决我在到达最终return语句之前函数完成的问题。 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. 正如Bergi所说,请使用可用的承诺。
But since Node 8 there is a promisify: 但自从节点8开始,就有了一个承诺:
Or use bluebird: 或使用蓝鸟:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.