promisebluebirdwhen-js

Need correct call to Promise reduce (when.reduce )


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.


Solution

  • 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.