【问题标题】:How to return promise with a return value如何用返回值返回承诺
【发布时间】:2017-10-09 02:14:59
【问题描述】:

getAccomodationCost 是一个函数,它期望返回一个带有返回值的承诺。现在它抛出一个错误 resolve is undefined.

然后在 promise 内的 resolve(JSON.parse(JSON.stringify(result))) 行抛出此错误消息。如果我将关键字resolve替换为return,那么主函数中的Promise.all调用将失败。

谁能帮我从下面的函数返回一个返回值 JSON.parse(JSON.stringify(result)) 的承诺。

  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()(而不仅仅是调用它)。其次,我不知道您的聚合函数,但据我所知,您传入的函数中没有可访问的解析方法。请记住,您始终必须返回结果,以便您可以链接承诺。
  • 您需要创建第二个new Promise 以获取resolve 用于hotelModel.aggregate 回调

标签: javascript node.js promise


【解决方案1】:

如果可能,让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 以返回一个 Promise,您将需要创建另一个 Promise 并从 .then(function (duration) 返回它,类似于您为 getHospitalStayDuration 所做的那样。

【讨论】:

    【解决方案2】:

    Promise 只能完成一次。 resolve() 在函数内被调用两次,resolve 未在 .then() 内定义。 resolvePromise 构造函数执行器函数中定义。在.then() 中应使用第二个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)))          
             })
           })
         });
    }
    

    【讨论】:

    • 有什么方法可以通过 getAccomodationCost 函数的返回值返回 accomodationCostPromise?
    猜你喜欢
    • 2016-06-15
    • 2015-10-30
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多