【发布时间】:2017-12-10 21:24:14
【问题描述】:
我是 Node 的新手,我正在使用它编写一些调用外部 API 的 Firebase 云函数。我在与承诺作斗争。我知道如何使用回调,但我不知道如何将回调转换为承诺。我想在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,
});
};
【问题讨论】:
-
不要让
wiwAPICreateJobSite使用callback参数——只要return承诺.post(…)已经给你了! -
我按照你的建议做了并更新了上面的代码。但我无法弄清楚如何将承诺链接在一起,这样它们就不会像我上面那样嵌套......如果你能展示一个非常感激的例子
-
我在您的代码中没有看到任何有问题的嵌套。您可能希望避免在单元素数组上使用
Promise.all,您可以通过unnest 调用.then(_ => true),但其余的都很好。
标签: javascript node.js google-cloud-functions