首页 文章

如何使用返回值返回promise

提问于
浏览
0

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 回答

  • -2

    Promise 只能履行一次 . resolve() 在函数内被调用两次, .then() 未在 .then() 中定义 . resolvePromise 构造函数执行函数中定义 . 第二个 Promise 应该在 .then() 中使用 .

    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)))          
             })
           })
         });
    }
    
  • 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 所做的操作 .

相关问题