【发布时间】:2016-11-13 00:44:47
【问题描述】:
我正在使用流行的节点请求模块为数组中的每个项目运行 HTTP GET 请求;然后在数组的最后一项运行一个函数。我的代码是这样的:
const request = require('request');
var arr = ['John', 'Jane', 'Marry', 'Scarlet'];
var x = 0;
arr.every(function (i) {
x++;
/*instead of waiting for request, it adds x and moves on making x
3 when the first request finally runs*/
request({
url: 'http://localhost:8810/getLastName?firstName=' + i
}, function (error, response, body) {
//execute some code
if(x==arr.length){
//therefore this function is run for each item in the array.
// it should run only once per array.
}
})
return true;
})
我希望在不编写大量代码的情况下实现这一目标,从而使我的代码保持美观和整洁。
编辑:我不想按顺序运行它。我不介意它并行运行,但我只是想在完成时触发一个函数一次。
【问题讨论】:
-
request()是异步的。它不会阻塞。您必须使用承诺或回调来编写代码,以跟踪每个异步操作的完成时间。您是要序列化请求(一次一个)还是并行运行它们并只知道它们何时完成? -
我只想知道它什么时候完成,以便我可以运行最后一个函数一次。
-
我试试看。
标签: javascript node.js