2

Here is the code I have:

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

What is the best way to handle it by using Bluebird Promises?

The most confusing thing to me is this line:

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

service.createChat should have an access to both service.findClient() and service.findChat() results.

Nazar
  • 1,769
  • 1
  • 15
  • 31
  • Have you tried anything yourself? I can't tell what that code does, so it's hard to know how to rewrite it using a different methodology - you at least have a clue as to what it's purpose is – Jaromanda X Aug 23 '16 at 03:56
  • @JaromandaX I've updated my question. – Nazar Aug 23 '16 at 04:10
  • Your solution is looking good. If it works, why not post it as an answer instead of a question update? – Tomalak Aug 23 '16 at 04:35
  • You don't really need the `return`, though. `.then((client) => [client, service.findChat(client)])` – Tomalak Aug 23 '16 at 04:41
  • If you don't mind an extra lib you could check out this https://github.com/backhand/auto-promise – unflores Dec 14 '18 at 15:07

2 Answers2

0

You could look at other already created modules like async-bluebird, or you could roll your own. By your question, it looks as though you don't necessarily need your own auto() promise implementation, just a working version of your example. In that case, you could achieve it by using a combination of chaining, and the all() function. For example (untested and off the top of my head):

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

Firstly, I create a promise from the findClient function, and then I create an array of required promises for the all function. The first is the initial promise, while the second is a chained version of the first into the second function. When both of those have completed, the all function returns the results of both promises into a results array.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
0

I guess I've found the solution:

service.findClient(message)
    .then((client) => [client, service.findChat(client)])
    .spread(service.createChat)
    .then(service.emitChatEvent)
    .then(service.editMenu)
    .catch(service.handleError);
Nazar
  • 1,769
  • 1
  • 15
  • 31