3

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

Fiscet
  • 31
  • 1
  • 1
  • 4

2 Answers2

4

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.
    });
Shilly
  • 8,511
  • 1
  • 18
  • 24
  • Hi, thanks for your help, I also thought to solve it as you suggested, but "products" from the first example reamin as initialized, "prodPromised" of the second example is undefined. – Fiscet Feb 16 '18 at 10:34
  • UPDATE in the second example i forgot the return. Anyway, the global property remains as initialized :-( – Fiscet Feb 16 '18 at 10:39
  • You'll have to show the rest of the code then. The only way `products` stays `null` in the first example, is when `getProducts()` doesn't return anything. Or if you try to continue synchronous code after. I've updated my first example. – Shilly Feb 16 '18 at 10:49
  • SOLVED I think there was a "timing" problem. I mean, when I called the global property from the second method, the data weren't set yet! So I used a deferred call with a jquery $.when :-) – Fiscet Feb 16 '18 at 10:52
  • Yeah you probably tried using products outside a `.then()` function right? – Shilly Feb 16 '18 at 10:52
  • Yes, from another method :-) – Fiscet Feb 16 '18 at 11:01
0

If createCatName is a synchronous function you can do the following

const products = global.getProducts().then(
  products=>
    products.map(self.createCatName)
);

If createCatName is an asynchronous function you do do this

const products = global.getProducts().then(
  products=>
    Promise.all(
      products.map(self.createCatName)
    )
);

when you want to use products then you can use the promise of products like so:

products.then(
  products=>{
    //use products here
  }
).catch(
  err=>console.warn("Something went wrong getting products:",err)
);

The value products is not an actual list of products but a list of products that may or may not be available in the future (it may not if there was an error).

So if you want to access products you always have to access it as a promise, you can use async await syntax but if you don't know what a promise is then please learn that first.

Async functions have await but actually return a promise immediately so anything outside the async function is handed a promise immediately and does not get the awaited result.

More on why and how on promises can be found here.

HMR
  • 37,593
  • 24
  • 91
  • 160
  • 1
    Hi HMR, I don't know why but i haven't sse your answer! Yes it's great your solution, I haven't thought about the ".map" ... thanks :-) – Fiscet Feb 16 '18 at 14:16