如何用返回值返回承诺 [英] How to return promise with a return value

查看:64
本文介绍了如何用返回值返回承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

getAccomodationCost is a function which is expected to return a promise with a return value. Now It's throwing an error resolve is undefined.

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

This error message is thrown at line resolve(JSON.parse(JSON.stringify(result))) inside promise then. If i replace keyword resolve with return then Promise.all call in the main function will fail.

有人可以帮助我从下面的函数中返回一个带有返回值 JSON.parse(JSON.stringify(result)) 的承诺.

Can some one help me to return a promise with a return value JSON.parse(JSON.stringify(result)) from the below function.

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

推荐答案

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

A Promise can only be fulfilled once. resolve() is called twice within function, resolve is not defined within .then(). resolve is defined within Promise constructor executor function. A second Promise should be used within .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)))          
         })
       })
     });
}

这篇关于如何用返回值返回承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆