Last active
December 18, 2015 03:09
-
-
Save cowboy/5716480 to your computer and use it in GitHub Desktop.
when.js promise callback nesting question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
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
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.