使用 async.map 保留结果顺序
Preserve order of results with async.map
我需要进行多个异步调用,并确保结果与调用保持相同的顺序。我如何使用 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]
});
The results array is not necessarily sorted by order of calls
It can be [item2, item3, item1]
嗯,没有。你为什么这么认为? The docs 明确说明:
the results array will be in the same order as the original arr
.
我需要进行多个异步调用,并确保结果与调用保持相同的顺序。我如何使用 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]
});
The results array is not necessarily sorted by order of calls
It can be[item2, item3, item1]
嗯,没有。你为什么这么认为? The docs 明确说明:
the results array will be in the same order as the original
arr
.