Kin
Kin

Reputation: 4596

Is it possible somehow run sync loop with Promises?

So I have simple loop with function which retunr Promise. Looks it like this:

for (var i = 0; i < categories.length; i++) {
    parseCategory(categories[i]).then(function() {
        // now go to the next category
    })
}

Is it possible somehow to wait until first function will be ended and the iterate to next element?

P.S. It's not necessary to use promises.

Upvotes: 0

Views: 81

Answers (3)

Paul
Paul

Reputation: 141887

If you want to do it in ES6 without a library:

var parseCategoryPromise = Promise.resolve();
for (var i = 0; i < categories.length; i++) {
  (function(i){
    parseCategoryPromise = parseCategoryPromise.then(function(){
      return parseCategory(categories[i])
    });
  })(i)
}

Upvotes: 1

idbehold
idbehold

Reputation: 17168

With await/async support you'd be able to do it pretty easily:

async function parseCategories (categories) {
  for (var i = 0; i < categories.length; i++) {
    await parseCategory(categories[i])
  }
}

Upvotes: 0

Chad Robinson
Chad Robinson

Reputation: 4623

If you are already using Promises, why not go all the way? The best Promise module, Bluebird, has a helper function specifically designed to iterate across an array, in series, with promises controlling the execution: http://bluebirdjs.com/docs/api/promise.mapseries.html. You use it like this:

Promise.mapSeries(categories, function(category) {
    // Parse the category, and return a value or a promise.
});

If parseCategory is a function defined elsewhere, you can even get more brief:

Promise.mapSeries(categories, parseCategory);

There is also a map sister function that executes the calls in parallel.

Upvotes: 0

Related Questions