Below is the code I'm trying to execute.
as described on the comment. I'm trying to have the updates to array 1 to be visible outside of .then() function.
can someone please help me understand why it happens? and how to have it visible outside of .then() function?
Thanks alot !
var array1 = [];
array2.forEach(function(item) {
// this is an async all to db.collection.findOne({_id: item.id});
object = getObject(item.id);
object.then(function(object) {
array1.push(object);
//if I print console.log(array1) here, I can see it getting updated
});
});
// this does not print anything
console.log(array1)
***EDIT
Though it was a duplicate of existing question, I was able to resolve the issue with provided example below
var array1 = [];
objectPromises = array2.map(item => function(item));
Promise.all(objectPromises).then(objects -> {
objects.forEach(function(object){
array1.push(object);
});
console.log(array1);
});
Thanks for the help!