Loop of promises does not return JSON in Node.js

Asked

Viewed 68 times

0

I have an array with the Events to be searched, to check if there is another one on the same day and time.

The code below returns me the existing events without problem, but only on the console.log. I must return to the Front and for now I’m not succeeding.

In short, my loop does not return the json I need to the front.

const searchEvent = async event => {
      const response = await Event.findOne({
        where: {
          [Op.or]: [
            {
              start: { [Op.between]: [event.start, event.end] },
            },
            {
              end: { [Op.between]: [event.start, event.end] },
            },
          ],
          room_id: event.room_id,
        },
      });
      return response;
    };

    const loadEvents = arrayOfEventsWithDateIniAndDateEnd.map(
      async event =>
        await searchEvent(event).then(result => console.log(result))
    );

    return res.json(loadEvents);

Return of Insomnia: inserir a descrição da imagem aqui

1 answer

4


The problem is here:

const loadEvents = arrayOfEventsWithDateIniAndDateEnd.map(
  async event =>
    await searchEvent(event).then(result => console.log(result))
  );

return res.json(loadEvents);

Note that you are mapping an array of values into an array of promises. Remember that asynchronous functions at all times will return a Promise.

Therefore, you need a means to ensure that all the promises of the mapped array are resolved before passing them to the method res.json.

To do this, just use the function Promise.all, that awaits the resolution of all the promises of the array, returning a new array with the values of each resolution.

Thus:

const loadEvents = arrayOfEventsWithDateIniAndDateEnd.map(
  async event =>
    await searchEvent(event)
  );

try {
  const resolvedValues = await Promise.all(loadEvents);
  return res.json(resolvedValues);
} catch (err) {
  return res.status(500).json({
    status: 'err',
    error: err.message
  });
}

Do not forget to treat for any mistakes. If one of the promises fails, Promise.all will also reject. Learn more in the documentation.

  • Opa @Luiz Felipe. I made the change but it didn’t work. In India you have the error: 500 Internal Server Error [Object Promise]. And on the console displays the error: "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client..."

  • You need to handle any rejections. Try to use try/catch, for example. Do not forget that, if one of the promises reject, the one returned by Promise.all will also be rejected.

  • I used Try/catch, me returns the : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. And the function is working because I can see the result on the console when I use the console.log.

  • You must be setting some header in another part of the application... It has nothing to do with the Promise.all (or anything from this question or answer). Learn more about this error here.

  • This controller is new, has little code, I treated all with "Return". But for testing, I removed all the res.json from it, leaving only the import of the Model and the sequelize with code that I posted. Still presents the error.

  • you are right. The problem is in the conditional routes I am using. I tested commenting and it worked. Now the problem is with the route. kkkkk

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.