Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js nodej识别asyntask的输出_Node.js_Asynchronous_Request_Synchronous - Fatal编程技术网

Node.js nodej识别asyntask的输出

Node.js nodej识别asyntask的输出,node.js,asynchronous,request,synchronous,Node.js,Asynchronous,Request,Synchronous,我是nodejs新手,我正在使用request nodejs api发出多个get请求, 这样,我就无法计算特定请求的输出。如何分别识别每个请求的响应?我使用for循环发送多个请求。如果我使用递归,它会再次变得同步,我只需要将请求与响应分离,因为它们太异步了。可能吗 在下面的代码中,变量“i”被上一次迭代替换 var list = [ 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%20Mo

我是nodejs新手,我正在使用request nodejs api发出多个get请求, 这样,我就无法计算特定请求的输出。如何分别识别每个请求的响应?我使用for循环发送多个请求。如果我使用递归,它会再次变得同步,我只需要将请求与响应分离,因为它们太异步了。可能吗

在下面的代码中,变量“i”被上一次迭代替换

var list = [ 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%20Mobiles%20with%20best&phrase2=Mobiles%20with%20best',
      'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%2520Mobiles%2520with%2520best&phrase2=what%20is%20a%20processor']

function ss(list){
    for(var i in list) {
        request(list[i], function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log( i + " " +body);
            }
        })
    }
}
您可以使用来执行异步请求。 具体来说,您可以使用
async.each
async.eachSeries

它们之间的区别在于,
each
将并行运行所有请求,就像
for
循环一样,但将保留上下文,而
eachSeries
将一次运行一个请求(只有在调用第一个循环的回调函数时,第二次迭代才会开始)。此外,对于更具体的用例还有其他选项(例如
eachLimit

使用
每个
的示例代码:

var list = [ 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%20Mobiles%20with%20best&phrase2=Mobiles%20with%20best',
      'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%2520Mobiles%2520with%2520best&phrase2=what%20is%20a%20processor']

function ss(list){
    async.each(list, function(listItem, next) {
        request(listItem, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log( listItem + " " +body);
            }

            next();
            return;
        })
    },
    //finally mehtod
    function(err) {
        console.log('all iterations completed.')
    })
}

它的工作方式类似于同步,所有响应都需要时间。我们是否可以像@Gilad Bison代码那样以异步方式识别特定请求的响应?正如我前面所述,您可以使用每个而不是每个序列。我编辑了答案