更好的方式来写这个承诺链

我在学习Node,并有一个函数recursion一个目录,并返回符合模式的文件的承诺。 这是工作相当不错,但我希望能够同时处理任何数量的types的文件,我链接的function是这样的:

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) }) }) }) 

但是当我添加更多types时,它可能会变得很sl sl。 我试过了

 Q.all([ findFiles(scriptLocation, '.type1.') , findFiles(scriptLocation, '.type2.') , findFiles(scriptLocation, '.type3.') ]).then(function(type1Files, type2Files, type3Files){ // all files returned in the first parameter... }) 

我喜欢第二个版本的语法,但是它并不完全符合我的要求,因为结果不是单独返回,而是汇总成单个结果。

我使用Q作为我的承诺库。

使用spread代替:

 Q.all([ findFiles(scriptLocation, '.type1.') , findFiles(scriptLocation, '.type2.') , findFiles(scriptLocation, '.type3.') ]).spread(function(type1Files, type2Files, type3Files){ // ... }) 

来自DOC :

如果你有一个数组的承诺,你可以使用spread作为替代。 传播函数将价值“传播”到执行处理程序的参数上。 拒绝处理程序将在失败的第一个标志处被调用。 也就是说,无论哪个收到的承诺失败,都会先被拒绝处理程序处理。