getAccomodationCost是预计将返回一个返回值的承诺的功能。现在这是抛出一个错误解决未定义。如何使用返回值返回承诺
此错误消息是在线解析(JSON.parse(JSON.stringify(结果)))内承诺抛出然后。如果我用return替换关键字解析,那么主函数中的Promise.all调用将失败。
有人能帮我与下面的函数返回值JSON.parse(JSON.stringify(结果))返回一个承诺。
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()(而不是仅仅调用它)。其次,我不知道你的聚合函数,但是从我所看到的,在你传入的函数中没有可解析的方法。记住,你总是必须返回结果,以便链接promise。 – sjahan
您需要创建第二个'新Promise'得到'resolve'为'hotelModel.aggregate' callbck – Bergi