使用async.map保持结果的顺序

Preserve order of results with async.map

本文关键字:结果 顺序 async map 使用      更新时间:2023-09-26

我需要进行多个异步调用,并确保结果保持在与调用相同的顺序。我如何用async库实现这一点?

async.map(['item1', 'item2', 'item3'], function (itemName, callback){
    // Ajax GET item on server
    // ...
    // Once we have the item, return it
    callback(null, item);
}, function(error, results){
    // The results array is not necessarily sorted by order of calls
    // It can be [item2, item3, item1]
    // I want to ensure it will always be [item1, item2, item3]
});

结果数组不一定按调用的顺序排序
可以是[item2, item3, item1]

没有

, 。你为什么这么想?文档明确声明:

结果数组的顺序将与原来的arr相同。