Need correct call to Promise reduce (when.reduce )

十年热恋 提交于 2020-01-05 07:21:26

问题


I have a processor function that takes a "cmd" object and returns a promise where the resolution is the same "cmd" object passed in (with a response key added). reduce here is 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)
   });

This does nothing, it does get to the .then but the array of promises never fires, never see the Debug running processor...

If I run just a single processor it works great cmd[0], cmds[1], etc.

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

What am I missing here? Their api and wiki examples aren't giving me any insight.

IMPORTANT UPDATE: The answer below does work but throws unhandled rejection errors. The culprit is the when library. It seems no longer active and has not been updated since node 6. I switched to bluebird and it works fine without any change to the code outlined below.


回答1:


I'm still not sure what you are looking for, but it might be

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

Before trying to understand when.reduce, you might want to have a look at the non-promise array reduce.



来源:https://stackoverflow.com/questions/40250132/need-correct-call-to-promise-reduce-when-reduce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!