【发布时间】:2017-10-09 02:14:59
【问题描述】:
getAccomodationCost 是一个函数,它期望返回一个带有返回值的承诺。现在它抛出一个错误 resolve is undefined.
然后在 promise 内的 resolve(JSON.parse(JSON.stringify(result))) 行抛出此错误消息。如果我将关键字resolve替换为return,那么主函数中的Promise.all调用将失败。
谁能帮我从下面的函数返回一个返回值 JSON.parse(JSON.stringify(result)) 的承诺。
var getAccomodationCost = function (req, res) {
var accomodationCostPromise = new Promise(function (resolve, reject)
{
getHospitalStayDuration(req, res, function (duration) {
resolve(duration)
})
})
.then(function (duration) {
hotelModel.aggregate([
//Some logic here
], function (err, result) {
resolve(JSON.parse(JSON.stringify(result)))
})
})
return accomodationCostPromise;
}
//Main function where the above snippet is called
const promise1 = somefunction(req, res);
const accomodationCostPromise = getAccomodationCost(req, res)
Promise.all([promise1,accomodationCostPromise])
.then(([hospitalInfo,accomodationCost]) => {
//Return some json response from here
}).catch(function (err) {
return res.json({ "Message": err.message });
});
【问题讨论】:
-
首先,您可能必须返回 hotelModel.aggregate()(而不仅仅是调用它)。其次,我不知道您的聚合函数,但据我所知,您传入的函数中没有可访问的解析方法。请记住,您始终必须返回结果,以便您可以链接承诺。
-
您需要创建第二个
new Promise以获取resolve用于hotelModel.aggregate回调
标签: javascript node.js promise