此代码与我的代码结构相同:
for (var i in UserNameArray)
{
var Urls = "https://some online api"+UserNameArray[i]+"api key";
//the url changes by plugging in the next array value every iteration.
request({
url: Urls,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
})
}
它正确地从URL返回一个json,但它打印出来,每个迭代的请求首先返回。如何更改我的代码,以便按照请求的顺序打印出请求?这很重要,因为我必须使用UserNameArray中的特定值遍历特定的JSON。
答案 0 :(得分:0)
在使用npm
安装异步之前尝试此操作var async = require('async');
async.forEach(UserNameArray, function (i, cb) {
var Urls = "https://some online api"+i+"apikey";
request({
url: Urls,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
cb();
})
});
答案 1 :(得分:0)
试试这个。
我将通过所有这些,并将响应存储在结果数组中(通过索引)。然后,当所有这些都完成后,它将进入最终回调,我们将它们(按顺序)打印到控制台。
var async = require('async');
var result = [];
async.eachOf(UserNameArray, function(name, i, cb) {
//the url changes by plugging in the next array value every iteration.
var Urls = "https://some online api"+UserNameArray[i]+"api key";
request({
url: Urls,
json: true
}, function (error, response, body) {
// checking if something went wrong..
if (error) return cb(error);
if (!error && response.statusCode === 200) {
// storing the response to our result array
result[i] = body;
// do a callback, telling that we are done here
cb();
}
})
}, function(err) {
// all done.
// lets print the errors if something went wrong
if (err) console.error(err.message);
// lets print our results
for(var i=0; i<result.length; i++) {
console.log(result[i]);
}
});