2017-09-14 70 views
0

我在nodejs中使用請求庫。我需要在請求中調用新的url,但我無法加入響應,因爲它是異步的。如何發送變量a,如以下請求中所示,其中包含請求的請求結果。nodejs中的請求中的請求

request({ 
    url: url, 
    json: true 
}, function (error, response, body) { 
    var a = []; 
    a.push(response); 
    for (i = 0; i < a.length; i++) { 
     if (a.somecondition === "rightcondition") { 
      request({ 
       url: url2, 
       json: true 
      }, function (error, response, body) { 
       a.push(response); 
      }); 
     } 
    } 
    res.send(a); 
}); 
+0

將res.send移動到第二個a.push下方。你需要什麼? – spiritwalker

+0

@spiritwalker第二次請求中有條件。編輯 – kinkajou

+0

沒有問題,如果有條件或沒有,你需要確保res.send不會觸發外部的第二個回調。因此,在編輯中移動res.send旁邊的for循環 – spiritwalker

回答

1

您的代碼似乎是正確的,你想要什麼。您只是在錯誤的回調中發送回覆。移動它,以便它只在第二個請求完成後發送:

request({ 
    url: url, 
    json: true 
}, function (error, response, body) { 
    var a = []; 
    a.push(response); 
    request({ 
     url: url2, 
     json: true 
    }, function (error, response, body) { 
     for(i=0;i<a.length;i++){ 
      if(a.somecondition === "rightcondition"){ 
       a.push(response); 
      } 
     } 
     res.send(a); // this will send after the last request 
    }); 
}); 
+0

實際上請求是在for循環內。我的錯 ! – kinkajou

0

您可以使用async waterfall

'use strict'; 

let async = require('async'); 
let request = require('request'); 

async.waterfall([function(callback) { 
    request({ 
     url: url, 
     json: true 
    }, function(error, response, body) { 
     callback(error, [response]); 
    }); 
}, function(previousResponse, callback) { 
    request({ 
     url: url2, 
     json: true 
    }, function(error, response, body) { 
     for(i=0;i<previousResponse.length;i++){ 
      if(previousResponse.somecondition === "rightcondition"){ 
      previousResponse.push(response); 
     } 
     } 
     callback(error, previousResponse); 
    }); 
}], function(err, results) { 
    if (err) { 
     return res.send('Request failed'); 
    } 
    // the results array will be final previousResponse 
    console.log(results); 
    res.send(results); 
}); 
+0

我編輯了問題 – kinkajou