QUESTION:
I am trying to assign to global arrays the results of queries to my MongoDB database efficiently. I essentially tried to store the references to the global arrays inside an array so that I could assign to all of them the results of the queries inside a for loop.
This does not seem to be possible. What would you suggest ?
CODE:
var arrays = [global.array1, global.array2, global.array3];
var colsArray = ["array1","array2","array3"];
var promises = colsArray.map(col => global.fetchCollection(col));
Promise.all(promises).then(responses => {
for (var d = 0; d < responses.length; d++) {
arrays[d] = responses[d];
}
console.log("VALUE INSIDE ARRAY of global.arrays: "+arrays[0]);
console.log("VALUE OF global.array is still : "+global.array1);
})
OUTPUT:
VALUE INSIDE ARRAY of global.arrays:: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
VALUE OF global.array is still : undefined
N.B.:
This would work of course. But quite unsatisfactory of course:
var arrays = [global.array1, global.array2, global.array3];
var colsArray = ["array1","array2","array3"];
var promises = colsArray.map(col => global.fetchCollection(col));
Promise.all(promises).then(responses => {
global.array1 = responses[0];
global.array2 = responses[2];
global.array3 = responses[3];
})
EDIT:
This does not work:
var arrays = [global.array1, global.array2, global.array3];
var colsArray = ["array1","array2","array3"];
var promises = colsArray.map(col => global.fetchCollection(col));
Promise.all(promises).then(responses => {
for (var d = 0; d < responses.length; d++) {
arrays[colsArray[d]] = responses[d];
}
console.log("VALUE INSIDE ARRAY of global.arrays: "+arrays[0]);
console.log("VALUE OF global.array is still : "+global.array1);
})