1

this is my second Node project. I am using Node, Express, MySQL.

What I am doing is, I have an array of names of users that have posted something, I then loop over those names and for each of them I do a connection.query to get their posts and I store those into an array(after that I do some other data manipulation to it, but that's not the important part)

The problem is: my code tries to do that data manipulation before it even receives the data from the connection.query!

I google-d around and it seems async await is the thing I need, problem is, I couldn't fit it in my code properly.

             // namesOfPeopleImFollowing is the array with the names
             namesOfPeopleImFollowing.forEach(function(ele){



             connection.query(`SELECT * FROM user${ele}posts`, function(error,resultOfThis){
              if(error){
                console.log("Error found" + error)
              } else {                        
                allPostsWithUsername.push([{username:ele},resultOfThis])                                              
              }
            })                 
          })

          console.log(JSON.stringify(allPostsWithUsername)) // This is EMPTY, it mustn't be empty.

So, how do I convert that into something which will work properly?

(Incase you need the entire code, here it is: https://pastebin.com/dDEJbPfP though I forgot to uncomment the code)

Thank you for your time.

  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Gabriel Carneiro May 15 '18 at 11:07

1 Answers1

1

There are many ways to solve this. A simple one would be to wrap your function inside a promise and resolve when the callback is complete.

const allPromises = [];
namesOfPeopleImFollowing.forEach((ele) => {
  const myPromise = new Promise((resolve, reject) => {
    connection.query(`SELECT * FROM user${ele}posts`, (error, resultOfThis) => {
      if (error) {
        reject(error);
        console.log(`Error found${error}`);
      } else {
        resolve({ username: ele });
      }
    });
  });
  allPromises.push(myPromise);
});

Promise.all(allPromises).then((result) => {
  // your code here
})

You can read more about promise.all here

AbhinavD
  • 6,892
  • 5
  • 30
  • 40