Home > front end >  map function concludes after one successful execution
map function concludes after one successful execution

Time:07-05

I am trying to map an array and fetch relevant data from MySQL and then again map the array returned by MySQL and send tweets. With this logic, the app only sends tweet for one element in the array. But, it actually needs to send multiple tweets as it maps through the array. Here is the code:

array.items.map(item => {
  con.query(`SELECT username FROM users where country="${item.country}"`, async function (err, result, fields) {
    if (err) throw err;
    console.log(result);

    result.length > 0 && result.map(async user => {
      try {
        await sendTweet(`Hello ${user.username}, your selected country is ${item.country}`);
      } catch (error) {
        console.error(error.body)
        return false
      }
    })
  });
});

What am I doing wrong here? I'd appreciate any help. Thank you.

CodePudding user response:

It seems there's no need to async and await.

var array = [1, 2, 3];
array.map(item => {

  // con.query
  setTimeout(function(err, result, fields) {
    if (err) throw err;

    result = [11, 22, 33];

    result.length > 0 && result.map(user => {
      try {

        // sendTweet
        setTimeout(function() {
          console.log(`Hello ${user.username}, your selected country is ${item.country}`);
        }, 500);

      } catch (error) {
        console.error(error)
        return false
      }
    })
  }, 500);
});

CodePudding user response:

I think you can use the function Promise.all

if (result.length) {
  try {
      await Promise.all(result.map(user => {
          return sendTweet(`Hello ${user.username}, your selected country is ${item.country}`);
      }));
  } catch(e) {
      //Handle the error
  }
}

CodePudding user response:

This is how I would maybe write it

async function tweetAll(item, error, users) {
  if(error) {
    console.log('error', error.message)
  }
  else {
    for(user of users) {
      await sendTweet(`Hello ${user.username}, your selected country is ${item.country}`)
    }
  }
}

for(item of array.items){
  con.query(`SELECT username FROM users where country="${item.country}"`, (error, users) => tweetAll(item, error, users))
}
  • Related