Skip to content
Brian Cavalier edited this page Feb 2, 2012 · 2 revisions

The Promises of when.all/some/map resolve to an array, so callbacks registered with them always receive an array as their one and only parameter. This makes it easy, for example using when.all, to build up an array of Promises and do something when all of them resolve, even when the size of the input array of Promises might vary.

However, sometimes it can also be useful to use callbacks that accept multiple parameters instead of an array of results. This can be especially useful when reusing existing functions as callbacks. For example, say we have a function to display information about a parent and child:

function showParentAndChild(parent, child) {
	// ...
}

To use this function as a callback to when.all(), we'd need to wrap it, which adds "unnecessary" code and obscures the intent:

when.all([fetchParent(), fetchChild()],
	function(parentAndChild) {
		showParentAndChild(parentAndChild[0], parentAndChild[1]);
	}
});

We can use the when/apply module to adapt the existing showParentAndChild() function more easily. Here is the equivalent version using when/apply, which maps the array results onto the arguments of the showParentAndChild

when.all([fetchParent(), fetchChild()],
	apply(showParentAndChild)
);
Clone this wiki locally