2017-06-01 62 views
3

我試圖用不同的URL調用getPromise函數來返回不同的承諾,但在第二個承諾的成功函數中得到未定義。重複使用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) 
     }); 
+1

你應該不會返回第二個'getPromise(...)'? – tanmay

+0

開始使用'async/await'並全部清除 – 2017-06-01 06:21:09

回答

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

確保您返回從承諾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

+0

它在加入返回後有效,但我不明白這一點, 沒有調用getPromise已經返回的承諾。 –

+0

再次說明:無論您從*返回*然後回調都會傳入下一個回調函數。所以,如果你想讓'getPromise'返回的promise在下一個'then'回調中可用,你需要從前一個返回。 – dfsq

+0

我認爲調用getPromise實際上是將承諾返回到下一個。現在感謝了 –

0

你缺少一個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) 
    });