Reusing promises

I am trying to call getPromise function with different urls to return different promises, but getting undefined in the second promise then success function.

var http=require('http');
var URL='http://localhost:3000';

var getPromise=function(url){
    var promise=new Promise(function(resolve,reject){
        http.get(url,function(response){
            if(response.statusCode < 200 || response.statusCode > 299){
                reject(new Error('ErrorCode '+response.statusCode))
            }
            var result="";
            response.on('data',function(chunk){result +=chunk;} )
            response.on('end',function(){resolve(result);} )
        })
    });
   return promise;
}



getPromise(URL+'/olympic/2016/ranking/4')
      .then(function(data){
         console.log("Response "+JSON.parse(data).Country);
         getPromise(URL+'/iso/country/'+JSON.parse(data).Country);
      })
      .then(function(data){
        console.log("Data "+data)
      })
      .catch(function(err){
         console.log(err)
      });

      

+3


source to share


4 answers


Make sure you return the data from the promise then

:

getPromise(URL+'/olympic/2016/ranking/4')
  .then(function(data){
     console.log("Response "+JSON.parse(data).Country);
     return getPromise(URL+'/iso/country/'+JSON.parse(data).Country);
  })
  .then(function(data){
    console.log("Data "+data)
  })
  .catch(function(err){
     console.log(err)
  });

      



Whatever you return from the callback then

will be passed down the promise chain. You are not returning anything right now, so you are implicitly returning undefined

.

+3


source


You need to return data for the next "then" to get it.



getPromise(URL+'/olympic/2016/ranking/4')
      .then(function(data){
         console.log("Response "+JSON.parse(data).Country);
         return getPromise(URL+'/iso/country/'+JSON.parse(data).Country);
      })
      .then(function(data){
        console.log("Data "+data)
      })
      .catch(function(err){
         console.log(err)
      });

      

0


source


You can change the function

getPromise(URL+'/olympic/2016/ranking/4')
      .then(function(data){
         console.log("Response "+JSON.parse(data).Country);
         getPromise(URL+'/iso/country/'+JSON.parse(data).Country)
         .then(function(data){
           console.log("Data "+data)
         });
      })

      .catch(function(err){
         console.log(err)
      });

      

0


source


You are missing return

:

getPromise(URL+'/olympic/2016/ranking/4')
  .then(function(data){
     console.log("Response "+JSON.parse(data).Country);

     /////////// here
     return getPromise(URL+'/iso/country/'+JSON.parse(data).Country);
  })
  .then(function(data){
    console.log("Data "+data)
  })
  .catch(function(err){
     console.log(err)
  });

      

0


source







All Articles