[英]How do I execute async.map function in order of array contents
I've got the following code routine that works great. 我有下面的代码例程,效果很好。 The only problem is that I need the results to come back in the same order of the
links
array. 唯一的问题是,我需要结果以
links
数组的相同顺序返回。 For example I need the results of the google.com link to come back first, then yahoo, etc. The code currently returns in a "random" order. 例如,我需要先返回google.com链接的结果,然后再返回yahoo,等等。该代码当前以“随机”顺序返回。
var Nightmare = require('nightmare');
var async = require('async');
var links = [
"http://www.google.com",
"http://www.yahoo.com",
"http://www.bing.com",
"http://www.aol.com",
"http://duckduckgo.com",
"http://www.ask.com"
];
var scrape = function(url, callback) {
var nightmare = new Nightmare();
nightmare.goto(url);
nightmare.wait('body');
nightmare.evaluate(function () {
return document.querySelector('body').innerText;
})
.then(function (result) {
console.log(url, result);
})
nightmare.end(function() {
callback();
});
}
async.map(links, scrape);
UPDATE: Thanks @christophetd. 更新:谢谢@christophetd。 Here is my revised working code:
这是我修改后的工作代码:
var Nightmare = require('nightmare');
var async = require('async');
var links = [
"http://www.google.com",
"http://www.yahoo.com",
"http://www.bing.com",
"http://www.aol.com",
"http://duckduckgo.com",
"http://www.ask.com"
];
var scrape = function(url, callback) {
var nightmare = new Nightmare();
nightmare.goto(url);
nightmare.wait('body');
nightmare.evaluate(function () {
return document.querySelector('body').innerText;
})
.then(function (result) {
callback(null, url+result);
});
nightmare.end();
}
async.map(links, scrape, function (err, results) {
if (err) return console.log(err);
console.log(results);
})
From the official async documentation : 从官方异步文档中 :
the results array will be in the same order as the original collection
结果数组将与原始集合的顺序相同
Which is pretty easy to verify: 这很容易验证:
// This function waits for 'number' seconds, then calls cb(null, number)
var f = function (number, cb) {
setTimeout(function () {
cb(null, number)
}, number * 1000)
}
async.map([4, 3, 2, 1], f, function (err, results) {
console.log(results); // [4, 3, 2, 1]
})
As you can see in the code above, even if the processing of the argument 4
by f
takes more time than the element 3
, it will still be first in the results. 如您在上面的代码中看到的那样,即使
f
对参数4
的处理比元素3
花费的时间更多,它仍将是结果的第一位。
In the case of your code, writing: 对于您的代码,编写:
async.map(links, scrape, function (err, results) {
if (err) {
// handle error, don't forget to return
}
// results will be in the same order as 'links'
})
Should give you the expected result. 应该给你预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.