I have method that resolves a promise that retrieves some Products
global.getProducts().then(function (prodPromised) {
For each prodPromised I have a Category ID but I also want the Category Name. So, I create an array of promises in which I assing the Category Name to each Product.
var products = [];
for (var i = 0; i < prodPromised.length; i++) {
promises.push(self.createCatName(prodPromised[i]));
}
After that I resolve the promises ...
Promise.all(promises).then((products) => {
... I loop them for some operations
for (var i = 0; i < products.length; i++) {
The problem is that I'd like to store the array products in a "upper" position so to use it for another method.
I suppose there's something related to the hoisting, but I dont' understand how to do it :-(
Thanks
You can either create a variable that you assign the promises to. Keep in mind that you have to continue with async code!
let products = null;
global
.getProducts()
.then(function (prodPromised) {
products = prodPromised;
})
This wont work:
let products = null;
global
.getProducts()
.then(function (prodPromised) {
products = prodPromised;
});
products.forEach( function( product ) {
// do stuff
} );
But this should:
let products = null;
global
.getProducts()
.then(function (prodPromised) {
products = prodPromised;
})
.then(function() {
products.forEach( function( product ) {
// do stuff
} );
});
Or alternatively, and this is my own preferred solution, because you don't have to make a variable for it outside the scope. Anything you return from a .then() callback, will be available in the next:
global
.getProducts()
.then(function (prodPromised) {
// do first stuff
return prodPromised;
})
.then(function (prodPromised) {
// do second stuff.
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With