2017-09-14 113 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