如何按照数组内容的顺序执行async.map函数

我有下面的代码例程,很好用。 唯一的问题是,我需要的结果回来的links数组相同的顺序。 例如,我需要首先返回google.com链接的结果,然后是雅虎等。代码当前以“随机”顺序返回。

 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); 

更新:谢谢@christophetd。 这是我修改的工作代码:

 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); }) 

从官方的asynchronous文档 :

结果数组将与原始集合的顺序相同

这很容易validation:

 // 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] }) 

正如你在上面的代码中看到的那样,即使f中的参数4的处理花费比元素3更多的时间,它仍然是结果中的第一个。


在你的代码的情况下,写:

 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' }) 

应该给你预期的结果。