0

I want to send an array of messages sequentially (in the same order of the given array) to the Messenger Send API.

When I am sending two messages, like so:

import Promise from 'bluebird';

const message1 = {...};
const message2 = {...};

const send = (message) => {
    return () => {sendAPI.post('/', message)};
}

let promises = [ send(message1), send(message2) ];
Promise.each(promises, (promise) => {
    console.log(promise);
    return promise();
});

the messages arrive in random order, but the console.log(promise) returns the API calls in order? How can I sequentially send, using the Bluebird library, messages to the Messenger Send API?

DrDirk
  • 1,937
  • 3
  • 25
  • 36
  • 1
    The problem is in `return () => {sendAPI.post('/', message)};`. You're using a *verbose* arrow function (one with a function body), but not using `return`. So you're not returning the promise that `sendAPI.post` returns. Either use a *concise* arrow function, or use `return`. See the linked question's answers for details. – T.J. Crowder Jan 23 '18 at 18:51
  • @jfriend00: Thank you again for pointing out how I fundamentally misread the `send` function above at first. I've double-checked, and provided `sendAPI.post` returns a promise (and surely it does), the OP's code is fine other than the arrow function issue. :-) – T.J. Crowder Jan 23 '18 at 18:51
  • Side note: FWIW, you don't need the `send` function at all: `Promise.each([message1, message2], msg => sendAPI.post('/', msg).catch(/*...*/);` Side note 2: **always** check for errors (see the `catch` earlier in this comment), or return the promise to an outer layer that checks for errors. – T.J. Crowder Jan 23 '18 at 18:54
  • 1
    @T.J.Crowder - Ahh, we both missed something. I missed that the arrow function wasn't returning anything. – jfriend00 Jan 23 '18 at 18:57
  • 1
    Sorry, typo in the code above (missing `)`). Fixed: `Promise.each([message1, message2], msg => sendAPI.post('/', msg)).catch(/*...*/);` – T.J. Crowder Jan 23 '18 at 19:05
  • Ok thx. Problem solved! As @T.J.Crowder noted it was because I did not return the promise in my array function. – DrDirk Jan 24 '18 at 15:28

0 Answers0