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