I have this promise that creates a new Item
document if it's not found in the db, and then stores it in a previously created Collection
document..
The Collection document is the first string in an array, and any subsequent index in the array translates to one or more Item docs.
Promise.each "Resolves to the original array unmodified" and so the last return
within the Promise.each
is rendering the objects, but the subsequent .then
produces the original array..
Here's the promise (abbreviated for readability):
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;
});
And here's the last of the console.log
within the Promise.each:
allItems: [
[ { _id: 54eec5f2b9fb280000286d52,
name: 'one',
label: 54eec5f2b9fb280000286d51,
collection: 54eec5f2b9fb280000286d50,
__v: 0 },
{ _id: 54eec5f2b9fb280000286d54,
name: 'two',
label: 54eec5f2b9fb280000286d53,
collection: 54eec5f2b9fb280000286d50,
__v: 0 } ]
And then after the subsequent .then(function(allItems) {
here's the last console.log
:
allItems: [
[ 'collectionName', 'one', 'two' ]
Also, the variable itemSeries
that = Promise.each
later renders undefined
in a Promise.join?