1

I have a problem with async - await.

What is happening?

I have a function of callback that a sends an array of objects, with valid objects and invalid objects to other function.

In the function, I do the validation, if it is valid, and do a push to save it in an array.

And I want to pass it to another function JUST when it finalizes with all objects valid. But it passes one per one and not all.

Someone could help me ?

Function that I call the callback passing the array of objects valid or not:

const getNewNotification = async (callback) => {
  await pool.query('SELECT * from alerts', (err, res) => {
    if (err) {
      console.log(err)
    } else {
      const newsNotification = res.rows;
      callback(newsNotification)
    }
  })
}

Function that I make the push:

const sendNotification = async (notification, callback) => {
  let domain;
  let subdomain;
  let name;
  let userHistory;
  let userDescription;
  let sequenceHistory;

  let personYes = [];

  let person;
  await notification.map(async (user) => {
    // VERIFY IF THE OBJECT IS VALID
    await pool.query(`SELECT * from wfm where mail = '${user.id}''`, async (err, res) => {
      if (res.rows.length !== 0) {
        person = {
          domain: res.rows[0].domain_name,
          subdomain: res.rows[0].subdomain_name,
          name: res.rows[0].name,
          userHistory: user.id,
          userDescription: user.change_description,
          sequenceHistory: user.sequence,
        }
  
  // MAKE THE PUSH...
        await personYes.push(person);
callback2(personYes);
      }

Basically, i want that the function sendNotification send the data JUST when it to end, how i make it?

jbarros
  • 628
  • 10
  • 28
ELD
  • 168
  • 4
  • 14
  • No value is `returned` from `.map()`. `callback2` is not defined within `sendNotification` – guest271314 Feb 24 '19 at 17:56
  • It's unclear how getNewNotification and sendNotification are related, the question doesn't contain https://stackoverflow.com/help/mcve . You're misusing `async`. It shouldn't be used with callbacks. node-postgres supports promises. – Estus Flask Feb 24 '19 at 18:02

1 Answers1

2

I think this is happening because you are mixing 2 things, either you should use callback method without await statement or you should use Promise properly. In your case, you can fix it using -

Instead of this

await pool.query(`SELECT * from wfm where mail = '${user.id}''`, async (err, res) => {

});

You should use -

let response = await pool.query(`SELECT * from wfm where mail = '${user.id}'`)

You callback code can sit in bottom.

For more detail you can refer - https://node-postgres.com/guides/async-express

Ashvin777
  • 1,446
  • 13
  • 19