2017-09-26 135 views
0

我有两个相同长度的迭代,我需要同时循环。一个迭代是自定义对象的Map,另一个是对象的数组。我需要将数组的内容添加到Map中(通过一些辅助函数原型函数),最好是异步并发的。而且,这两个容器根据它们的顺序相互关联。因此,数组中的第一个元素需要添加到Map中的第一个元素。同时迭代两个相同长度的迭代

如果我是这样做同步,将是这个样子:

var map; 
var arr; 
for (var i = 0; i < arr.length; i++) { 
    // get our custom object, call its prototype helper function with the values 
    // in the array. 
    let customObj = map[i]; 
    customObj.setValues(arr[i]) 
} 

通常遍历数组异步并同时我用蓝鸟Promise.map。这将是这个样子:

var arr 
Promise.map(arr, (elem) => { 
    // do whatever I need to do with that element of the array 
    callAFunction(elem) 
}) 

这将是真棒,如果我可以做这样的事情:

var map; 
var arr; 
Promise.map(map, arr, (mapElem, arrElem) { 
    let customObj = mapElem[1]; 
    customObj.setValue(arrElem); 
}) 

有谁知道图书馆或一个聪明的方式来帮助我做到这一点的?

谢谢。

编辑:只是想添加一些关于存储在地图中的对象的澄清。地图以唯一值为键值,并且值与构成此对象的唯一值相关联。它的定义与此类似:

module.exports = CustomObject; 
function CustomObject(options) { 
    // Initialize CustomObjects variables... 
} 

CustomObject.prototype.setValue(obj) { 
    // Logic for adding values to object... 
} 

回答

1

,如果你已经知道了,那地图(我假设你真的是JavaScript的地图在这里,这是有序的)和数组的长度相同,则不需要映射功能,这既考虑数组和地图。其中之一就足够了,因为地图功能还给你一个索引值:

var map; 
var arr; 
Promise.map(map, (mapElem, index) => { 
    let customObj = mapElem[1]; 
    customObj.setValue(arr[index]); 
}); 
+0

这是完美的!在Promise.map文档中忽略了这一点。万分感谢! –

0

您可以使用执行所有给定异步函数的函数Promise.all

你应该知道,实际上node.js完全支持Promises,你不需要bluebirds了。

Promise.all(arr.map(x => anyAsynchronousFunc(x))) 
    .then((rets) => { 
     // Have here all return of the asynchronous functions you did called 

     // You can construct your array using the result in rets 
    }) 
    .catch((err) => { 
     // Handle the error 
    }); 
+0

我用蓝鸟来加速!我需要同时循环两个对象。我定义了一个自定义对象,并且该映射由许多这些自定义对象组成。我需要调用的帮助函数是该对象实例的成员函数,因此每次我调用它时,都会编辑该对象的特定实例。让我知道你是否需要更多的澄清。 –