蓝鸟诺言串行迭代,并解决修改数组?

我有这个承诺,创build一个新的Item文件,如果没有在数据库中find,然后将其存储在以前创build的Collection文档..

Collection文档是数组中的第一个string,数组中的任何后续索引都将转换为一个或多个Item文档。

Promise.each “解决原始数组未经修改” ,所以Promise.each的最后一个return是呈现对象,但后来。然后生成原始数组..

这是诺言(缩写为可读性):

 globalVar = true; collectionId = ""; var itemSeries = Promise.each(items, function(element) { if (globalVar == true) { return Models.Collection.findOneAsync({ "name": element }) .then(function(collection) { // promise chain similar to the following else.. // set the collectionId var to an _id }); } else { return Models.Items.findOneAsync({ "name": element }) .then(function(item) { if (item == null) { return Models.Labels.findOneAsync({ "title": element }) .then(function(label) { var newItem = new Models.Items({ name: element, label: label._id }); return newItem.saveAsync(); }).then(function() { return Models.Items.findOneAsync({ "name": element }); }).then(function(item) { item.collection = collectionId; return item.saveAsync(); }).then(function() { return Models.Items.findOneAsync({ "name": element }); }).then(function(item) { allItems.push(item); console.log("allItems: [ "); console.log(allItems); return allItems; }); } }); } }).then(function(allItems) { console.log("allItems: [ "); console.log(allItems); return allItems; }); 

以下是Promise.each中的最后一个console.log

 allItems: [ [ { _id: 54eec5f2b9fb280000286d52, name: 'one', label: 54eec5f2b9fb280000286d51, collection: 54eec5f2b9fb280000286d50, __v: 0 }, { _id: 54eec5f2b9fb280000286d54, name: 'two', label: 54eec5f2b9fb280000286d53, collection: 54eec5f2b9fb280000286d50, __v: 0 } ] 

然后在后面.then(function(allItems) {这里是最后一个console.log

 allItems: [ [ 'collectionName', 'one', 'two' ] 

另外,variablesitemSeries = Promise.each稍后在Promise.join中呈现undefined

.each函数不会改变通过链的值:

我简化你的代码,作为input我假设:

 var items = ['one','two']; 

对于你的代码:

 Promise.each(items, function(element) { return element+'.'; //return Promise.resolve(element+'.'); }) .then(function(allItems) { console.dir(allItems); }); 

结果仍然是['one','two']因为这是数组itemsparsing值。 每个返回值不影响传递给链接的值的内容。

另一方面.map函数会有这样的效果:

 Promise.map(items, function(element) { return element+'.'; //return Promise.resolve(element+'.'); }) .then(function(allItems) { console.dir(allItems); }); 

这里return值的值将被用来创build一个新的数组,然后传递给它。 这里的结果是['one.','two.']

出现在代码中的两个allItems是不同的对象。

编辑对于映射的串行迭代,我会写这样的帮助函数:

  function mapSeries(things, fn) { var results = []; return Promise.each(things, function(value, index, length) { var ret = fn(value, index, length); results.push(ret); return ret; }).thenReturn(results).all(); } 

资料来源: 实施Promise.series

Bluebird现在实现了一个mapSeries ,请参阅http://bluebirdjs.com/docs/api/promise.mapseries.html

它也看起来像Promise.each不幸在v3.xx中返回原始数组