Jensej
Jensej

Reputation: 1305

How execute synchronicity in javascript

I want to do somethink on array: skinydobazy after add new param check.

skinydobazy.forEach(function(klucz,index) {   
    getPrice(data.prices[0]).then(function(results) {

            var price = results.skinData.wep.median_price;
            if(price > 1)
            klucz.check = 1;

            console.log('HERE');

        });
  }); // end foreach 


  console.log(skinydobazy); //do sth after foreach

(after foreach loop) I want to do somethink with updateted skinydobazy. But I have a problem. Because first display skinydobazy, but should "HERE" and after should display skinydobazy.

Is any solutions? Thanks

Upvotes: 0

Views: 258

Answers (1)

Shashank
Shashank

Reputation: 13869

By using map instead of forEach, you can produce an array of Promises. You can then subscribe to the completion of all Promises in that array using Promise.all.

Promise.all(skinydobazy.map(function(klucz, index) {
  // Return the Promise that resolves on .then(fn)
  return getPrice(data.prices[0]).then(function(results) {

    var price = results.skinData.wep.median_price;
    if (price > 1)
      klucz.check = 1;

    console.log('HERE');

    // Resolve Promise with results
    return results;
  });
}).then(function(allResults) {
  // allResults will be an array of results
  console.log(skinydobazy);
});

Upvotes: 1

Related Questions