重用Promise创建

时间:2017-06-01 06:06:54

标签: javascript node.js promise es6-promise

我试图用不同的URL调用getPromise函数来返回不同的promise,但是在第二个promise中成功函数未定义。

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

4 个答案:

答案 0 :(得分:3)

确保您从承诺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)
  });

无论您从then回调中返回什么,都会在承诺链中进一步传递。现在你没有返回任何东西,因此隐含地返回undefined

答案 1 :(得分:0)

你必须为下一个'然后'返回数据才能接收它。

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

答案 2 :(得分:0)

您可以更改功能

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 :(得分:0)

您错过了entryway

return
相关问题