Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 848
mikemaccana Avatar asked Feb 15 '23 05:02

mikemaccana


2 Answers

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.

like image 153
Bergi Avatar answered Feb 17 '23 19:02

Bergi


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.

like image 26
Domenic Avatar answered Feb 17 '23 19:02

Domenic