如何创建类似 async.auto 的承诺链?

How to create async.auto-like promises chain?

这是我的代码:

async.auto({
    client: service.findClient,
    existingChat: ['client', service.findChat],
    chat: ['client', 'existingChat', service.createChat]
}, (err) => {
    if (err) return service.handleError(err);
    service.emitChatEvent();
    service.editMenu();
});

使用 Bluebird Promises 处理它的最佳方法是什么?

最让我困惑的是这一行:

 chat: ['client', 'existingChat', service.createChat]

service.createChat 应该可以访问 service.findClient()service.findChat() 结果。

您可以查看其他已创建的模块,例如 async-bluebird,或者您可以自己创建。根据你的问题,看起来你不一定需要自己的 auto() 承诺实现,只是你的示例的一个工作版本。在这种情况下,您可以通过结合使用链接和 all() 函数来实现。例如(未经测试且不在我的脑海中):

let fc = service.findClient(message);
Promise.all([fc, fc.then(service.findChat)])
       .then(service.createChat);

首先,我从 findClient 函数创建一个 promise,然后我为 all 函数创建一个必需的 promise 数组。第一个是初始承诺,而第二个是第一个到第二个函数的链式版本。当这两个都完成时,all 函数 returns 将两个承诺的结果放入结果数组中。

我想我找到了解决方案:

service.findClient(message)
    .then((client) => [client, service.findChat(client)])
    .spread(service.createChat)
    .then(service.emitChatEvent)
    .then(service.editMenu)
    .catch(service.handleError);