getAccomodationCost是一个函数,它应该返回一个带有返回值的promise . 现在它正在抛出错误解决方案未定义 .
然后在promise内部的行解析(JSON.parse(JSON.stringify(result)))中抛出此错误消息 . 如果我用return替换关键字resolve,则main函数中的Promise.all调用将失败 .
有人可以帮我从下面的函数返回一个带有返回值JSON.parse(JSON.stringify(result))的promise .
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 });
});
2 回答
Promise
只能履行一次 .resolve()
在函数内被调用两次,.then()
未在.then()
中定义 .resolve
在Promise
构造函数执行函数中定义 . 第二个Promise
应该在.then()
中使用 .如果可能的话
hotelModel.aggregate
返回一个承诺 . 这会使代码看起来像这样:如果您无法修改
hotelModel.aggregate
以返回承诺,则需要创建另一个承诺并从.then(function (duration)
返回该承诺,类似于您对getHospitalStayDuration
所做的操作 .