JS: what's the promises equivalent of async.each?

Problem

Seems like it's been announced today that promises will be in ES6.

I've never been a promises guy - epic chains of .then() seem more complex than a simple list of functions in async.waterfall() but it looks like I'm going to have to learn them anyway.

So what's the equivalent of the other very popular workflow, async.each()?

async.each(items, processItem, function(err){
    doSomething(err)
});

Eg, run a processItem function over each item, once all have completed, continue with doSomething (doing something different if any of the processItem()s screwed up).

  • How can I do this in promises?
  • Is there an official place for promises user docs (not the promises spec, actual example workflows and how you'd do them in promises) like there for async?
Problem courtesy of: mikemaccana

Solution

Is there an official place for promises user docs (not the promises spec, actual example workflows and how you'd do them in promises) like there for async?

We have been putting together a page of general promise resources on the Q wiki. In terms of workflows and composition, I believe "How to Compose Node.js Promises with Q" would be the most helpful; it isn't really Node.js-specific, despite the title.

Solution courtesy of: Domenic

Discussion

How can I do this in promises?

Assuming processItem does now not take a callback but returns a promise you would write

all(items.map(processItem)).then(doSomething);

Where all is your library's all function that takes an array of promises, like Q.all. If you don't have one, this simple-minded implementation will do:

function all(promises) {
    return promises.reduce(function(m, p) {
        return m.then(function(res) {
            return r.then(function(r) { return res.concat([r]); });
        });
    }, fulfill([]));
}

Is there an official place for promises user docs (not the promises spec, workflows and how you'd do them in promises) like there is async?

Nope. Every Promise library does have its own docs, and there are many tutorials on the web. "Official" are only the specs, which I think are short and understandable enough for the user to read though.

Discussion courtesy of: Bergi

This recipe can be found in it's original form on Stack Over Flow.