2017-10-08 84 views
-1

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 }); 
    });  
+0

首先,你可能必須返回hotelModel.aggregate()(而不是僅僅調用它)。其次,我不知道你的聚合函數,但是從我所看到的,在你傳入的函數中沒有可解析的方法。記住,你總是必須返回結果,以便鏈接promise。 – sjahan

+0

您需要創建第二個'新Promise'得到'resolve'爲'hotelModel.aggregate' callbck – Bergi

回答

-2

A Promise只能實現一次。 resolve()被稱爲函數內兩次,resolve沒有內.then()定義。 resolve被定義在Promise構造函數執行器函數中。應在0​​內使用第二個Promise

var getAccomodationCost = function (req, res) { 
    return new Promise(function (resolve, reject) { 
     getHospitalStayDuration(req, res, function (duration) { 
      resolve(duration)    
     }) 
    }) 
    .then(function (duration) { 
     return new Promise(function(resolve, reject) { 
     hotelModel.aggregate([ 
      //Some logic here 
     ], function (err, result) { 
      if (err) reject(err);   
      resolve(JSON.parse(JSON.stringify(result)))   
     }) 
     }) 
    }); 
} 
+0

有沒有辦法從getAccomodationCost函數返回值返回accomodationCostPromise? –

2

如果可能的話有hotelModel.aggregate返回承諾。這會使得代碼看起來是這樣的:

.then(function (duration) { 
    return hotelModel.aggregate([ 
     //Some logic here 
    ]).then(result => JSON.parse(JSON.stringify(result))) // Not sure why you're stringify/parsing 
}) 

如果您不能修改hotelModel.aggregate返回一個承諾,你將需要創建另一個承諾並返回,從.then(function (duration),類似於你是怎麼做到的getHospitalStayDuration