需要正确的承诺Promise减少(when.reduce) [英] Need correct call to Promise reduce (when.reduce )

查看:172
本文介绍了需要正确的承诺Promise减少(when.reduce)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理器函数,该函数接受一个"cmd"对象,并返回一个分辨率,其中分辨率与传入的同一"cmd"对象相同(添加了响应键). 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)
   });

这什么也不做,它确实到达了.then,但是承诺数组从未触发,也从未看到过Debug running processor...

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

如果我只运行一个处理器,则可以很好地使用cmd [0],cmds [1]等.

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

我在这里想念什么?他们的api和 wiki 实例并没有给我带来任何见识.

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

重要更新: 以下答案确实有效,但会引发未处理的拒绝错误.罪魁祸首是何时图书馆.从节点6开始,它似乎不再处于活动状态,并且未进行任何更新.我切换到了bluebird,并且可以正常运行,而无需更改下面概述的代码.

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.

推荐答案

我仍然不确定您要寻找什么,但可能是

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) {
    …
});

在尝试理解when.reduce之前,您可能希望了解一下没有承诺的

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

这篇关于需要正确的承诺Promise减少(when.reduce)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆