Sona Shetty
Sona Shetty

Reputation: 1047

How to return promise with a return value

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

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.

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

Upvotes: 0

Views: 2778

Answers (2)

Andy Gaskell
Andy Gaskell

Reputation: 31761

If possible have hotelModel.aggregate return a promise. That'd make the code look something like this:

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

If you cannot modify hotelModel.aggregate to return a promise, you will need to create another promise and return that from .then(function (duration), similar to how you did it for getHospitalStayDuration.

Upvotes: 2

guest271314
guest271314

Reputation: 1

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

Upvotes: -2

Related Questions