需要正确调用 Promise reduce (when.reduce)

Need correct call to Promise reduce (when.reduce )

我有一个处理器函数,它接受一个 "cmd" 对象和 returns 一个承诺,其中分辨率与传入的 "cmd" 对象相同(添加了响应键)。 reduce这里是when.reduce

 reduce = require('when').reduce;

  //return processor(cmds[0])
 return reduce(cmds, function(processor, cmd) {
     Debug.L1('running processor for component ', cmd.component)
     return processor(cmd)
   })
   .then(cmds => {
     Debug.L1('cmds with responses\n', cmds)
     let response = cmds.map(cmd => {
       return cmd.response
     })
     console.log('the complete response is\n', response)
   });

这什么都不做,它确实到达了 .then 但是承诺数组永远不会触发,永远不会看到调试 running processor...

如果我 运行 只有一个处理器,它会很好地运行 cmd[0]、cmds[1] 等

return processor(cmds[0])
//return reduce(cmds, function(processor,cmd) {
//       Debug.L1('running processor for component ', cmd.component)
//   return processor(cmd) })

我在这里错过了什么?他们的 api 和 wiki 示例没有给我任何见解。

重要更新: 下面的答案确实有效,但会引发未处理的拒绝错误。罪魁祸首是when库。它似乎不再活跃并且自节点 6 以来没有更新。我切换到 bluebird 并且它工作正常而无需对下面概述的代码进行任何更改。

我还是不确定你在找什么,但可能是

reduce(cmds, function(responses, cmd) {
    return processor(cmd).then(function(response) {
        responses.push(response); // or whatever
        return responses;
    });
}, []).then(function(responses) {
    …
});

在尝试理解 when.reduce 之前,您可能想看一下非承诺 array reduce