Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, global variable assignment from nested Promises

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

like image 599
Fiscet Avatar asked Jun 03 '26 22:06

Fiscet


1 Answers

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.
    });
like image 80
Shilly Avatar answered Jun 06 '26 11:06

Shilly