Reputation: 6888
I am learning Node and have a function that recurses a directory and returns promise of files that match a pattern. This is working pretty good, but I want to be able to handle files of any number of types simultaneously, and I am chaining the functions like this:
findFiles(scriptLocation, '.type1.').then(function (type1Files) {
console.log('type1Files: ' + type1Files)
findFiles(scriptLocation, '.type2.').then(function (type2Files) {
console.log('type2Files: ' + type2Files)
findFiles(scriptLocation, '.type3.').then(function (type3Files) {
console.log('type3Files: ' + type3Files)
})
})
})
But it could get pretty sloppy as I add more types. I tried
Q.all([
findFiles(scriptLocation, '.type1.')
, findFiles(scriptLocation, '.type2.')
, findFiles(scriptLocation, '.type3.')
]).then(function(type1Files, type2Files, type3Files){
// all files returned in the first parameter...
})
I like the syntax of the second version, but it doesn't quite do what I want, as the results are not returned individually but rolled up into a single result.
I am using Q as my promise library.
Upvotes: 2
Views: 80
Reputation: 3933
Use spread
instead:
Q.all([
findFiles(scriptLocation, '.type1.')
, findFiles(scriptLocation, '.type2.')
, findFiles(scriptLocation, '.type3.')
]).spread(function(type1Files, type2Files, type3Files){
// ...
})
From the DOCs:
If you have a promise for an array, you can use
spread
as a replacement for then. The spread function “spreads” the values over the arguments of the fulfillment handler. The rejection handler will get called at the first sign of failure. That is, whichever of the received promises fails first gets handled by the rejection handler.
Upvotes: 1