Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active December 18, 2015 03:09
Show Gist options
  • Save cowboy/5716480 to your computer and use it in GitHub Desktop.
Save cowboy/5716480 to your computer and use it in GitHub Desktop.
when.js promise callback nesting question
// I saw an example like this, but I don't like the nesting.
getThing().then(function(thing) {
return when.all(thing.ids.map(function(id) {
return getSubThing(id);
})).then(function(subthings) {
// doSomething(thing, subthings);
});
});
// Can `thing` be passed to when.all and this the next .then() ?
getThing().then(function(thing) {
return when.all(thing, thing.ids.map(function(id) {
return getSubThing(id);
}));
}).then(function(thing, subthings) {
// doSomething(thing, subthings);
});
// Do I need to concat `thing` and the array of subthings into one array?
getThing().then(function(thing) {
return when.all([thing].concat(thing.ids.map(function(id) {
return getSubThing(id);
}));
}).then(function(thing, subthings) {
// doSomething(thing, subthings);
});
// Or would I use when.join with when.map like this?
getThing().then(function(thing) {
return when.join(thing, when.map(thing.ids, function(id) {
return getSubThing(id);
});
}).then(function(thing, subthings) {
// doSomething(thing, subthings);
});
@scothis
Copy link

scothis commented Jun 5, 2013

This is as tight as I can get it. The kicker is the need to keep thing in scope, without that it could be much cleaner.

getThing().then(function (thing) {
  return when.join(thing, when.map(thing.ids, getSubThing));
}).then(function (things) {
  return doSomething.apply(undefined, things);
});

@briancavalier
Copy link

Two variants using join/spread:

getThing().then(function (thing) {
    // This is slightly deceptive, in that spread will
    // resolve the contents of this array for you
  return [thing, when.map(thing.ids, getSubThing)];
}).spread(doSomething);
// To be more explicit:
getThing().then(function (thing) {
  return when.join(thing, when.map(thing.ids, getSubThing));
}).spread(doSomething);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment