Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
map function concludes after one successful execution

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);
});

about 4 years ago · Juan Pablo Isaza Report

0

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
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

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))
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!