I’ve got some code shown below. Basically the following prints out “x” in the console fine.
let numbers = [];
for(var i = 0; i<10;i++){
test(i).then((x) => console.log(x));
}
What I am hoping to do though it to save the value “x” into the variable “numbers” and use it somewhere else out of the for loop. I’ve attempted the following but either way “numbers” is still an empty array, . I know it has to do with the scope of the variable but I am not sure how to fix it. Any help will be appreciated. Thanks.
let numbers = [];
for(var i = 0; i<10;i++){
test(i).then((x) => numbers = x);
}
console.log(numbers);
let numbers = [];
for(var i = 0; i<10;i++){
test(i).then((x) => numbers = x);
console.log(numbers);
}
Hi @markshaioms, the problem is not the scope here but that a promise resolves asynchronously, so when you console.log(numbers) the promises are still in a pending state. Also note that you’re assigning a new value to numbers in the success callback… I guess you’ll actually want to .push() it instead. Anyway you can wait for all promises to resolve using Promise.all() like so:
// Some test promise
const test = x => Promise.resolve(x)
// Create an array which is getting mapped to these test promises
const promises = Array.from({ length: 10 }, (_, i) => test(i))
// After all promises got resolved, log the results to the console
Promise.all(promises).then(console.log)
// Output: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Also, this way you don’t even need that numbers array; the results of all promises are directly getting passed to the success callback.