Home > Enterprise >  How can I map a JavaScript array to save every element to a database and return the saved item?
How can I map a JavaScript array to save every element to a database and return the saved item?

Time:12-22

I am working on an application that allows users to send an email to a list of contacts. Here is how the function that I am having trouble with works:

  • The email content is saved to the database.
  • The array of contacts is mapped. For every contact...
  • ...The contact is saved to the database.
  • ...An email is sent to the contact with a URL containing the email id and their contact id that the database generated.
  • ...The saved recipient should be but is not currently returned.
  • The array of saved contacts which are currently just empty objects :( is returned to the front end.

An empty object is returned for every contact instead of the actual contact, which is weird because I can console.log() the object within the map, and the contact's information is being sent in the email, so it definitely exists at some point.

Here is the code:

const postOne = async (req, res) => {
    const db = req.app.get("db");
    const { adviceRequest, recipients } = req.body;

    // ( Validation goes here )

    try {

      // Save the request.

      let [savedRequest] = await db.requests.postOne([
        adviceRequest,
        req.session.user.id,
      ]);

      // For every recipient...

      let savedRecipients = recipients.map(async (person) => {

        // ...Save them to the database.

        let [savedRecipient] = await db.responses.postOne([
          savedRequest.request_id,
          person.email,
          person.name,
          req.session.user.id,
        ]);

        // At this point, console.log(savedRecipient) shows the actual recipient, so it works.

        // ...Send them an email.

        await sendMail(savedRecipient, savedRequest);

        // ...Then add the saved recipient to the array that .map() generates.

        return savedRecipient;
      });

      // Send the request and the array of people back.

      return res.status(200).json([savedRequest, savedRecipients]);
    } catch (err) {
      return res.status(500).json(err);
    }
  },

The thing is, the array that the .map() returns is an array of empty objects. I do not know why. Inside the .map(), savedRecipient is defined as it should be, and the information there is successfully being used to send the required information via email. But what is returned to the front end is an array of empty objects--one for each contact.

If someone could tell me what I am doing wrong, I would appreciate it!

CodePudding user response:

You can try for loop to use async and await.

CodePudding user response:

let savedRecipients = recipients.map(async (person) =>

Property savedRecipients here is an array of promises. Try to resolve this promises, like this:

const savedRecipientsData = await Promise.all(savedRecipients);
  • Related