Nodejs承诺
我有一个函数调用序列,与ES6承诺连接。显然,这个实现有些问题,因为API调用的端点没有返回任何东西,浏览器也不能等待响应。Nodejs承诺
请指教。
module.exports.insertTreatmentDetails = function (req, res) {
var doctorId = 10000
var departmentId = 10000
var procedureid = 10000
var hospitalSchema = new hospitalModel();
var p = new Promise(function (resolve, reject) {
counterSchema.getNext('Treatment.doctor.doctorId', collection, function (doctorId) {
doctorId = doctorId;
})
counterSchema.getNext('Treatment.departmentId', collection, function (departmentId) {
departmentId = departmentId
})
counterSchema.getNext('Treatment.procedureid', collection, function (procedureid) {
procedureid = procedureid
})
}).then(function() {
setData()
}).then(function(){
hospitalSchema.save(function (error, data) {
if (error) {
logger.error("Error while inserting record : - " + error)
return res.json({ "Message": error.message.split(":")[2].trim() });
}
else {
return res.json({ "Message": "Data got inserted successfully" });
}
});
});
};
简短的回答是,你是不是叫resolve
或reject
在链中的第一个应许里面。承诺仍然在pending
状态。 Mozilla有很好的basic explanation of promises。
如何解决
它显示了要调用setData
之前检索doctorId
,departmentId
和procedureId
。您可以尝试将所有三个调用包装在一个承诺中,检查所有三个调用是否在每个回调中都返回了一些内容,但理想情况是每个异步任务都有一个承诺。
如果可以更改counterSchema.getNext
,那么可以让该函数返回一个承诺,而不是接受回调。如果不是的话,我会建议在每个电话中包装自己的承诺。为了保持最真实的你的代码,目前看起来,这可能是这样的:
const doctorPromise = new Promise((resolve, reject) =>
counterSchema.getNext('Treatment.doctor.doctorId', collection, id => {
doctorId = id;
resolve();
}));
然后,你可以更换一个调用的第一个承诺Promise.all
:
var p = Promise.all([doctorPromise, departmentPromise, procedurePromise])
.then(setData)
.then(/* ... */);
承诺允许您传递一个值直到下一步,所以如果你想摆脱你范围广泛的变量(或者在你调用setData
的同一步骤中设置它们),你可以通过resolve
作为你的回调counterSchema.getNext
,并收集值下一步(也是如果你有,你会怎么做退货承诺:
Promise.all([/* ... */])
.then(([doctorID, departmentID, procedureID]) => {
// If you aren't changing `setData`
doctorId = doctorID;
departmentId = departmentID;
procedureid = procedureID;
setData();
// If you are changing `setData`
setData(doctorID, departmentID, procedureID);
}).then(/* ... */).catch(/* I would recommend adding error handling */);
如何向响应对象返回一个值?看起来像我返回值的响应obejct不起作用 –
'new Promise(function(resolve,reject){'正在创建一个promise。里面的函数被赋予了两个更多的函数它可以调用:resolve和reject,调用resolve可以解决promise,下一个'.then'就会去,调用reject将导致promise被拒绝,并且找到下一个'.catch' 。你没有调用'resolve' –
感谢Brett.Hope的出色解释,这将有助于许多新蜜蜂理解诺言 –
您对Promise没有'catch'...如果在那里有任何错误,您永远不会知道它。 – jakerella