Home > front end >  Difficulties to perform operations synchronously with node and mysql
Difficulties to perform operations synchronously with node and mysql

Time:10-06

I'm working with these two functions:

const createProducts = async () => {
  const manufacturers = await getManufactuters()
  console.log(manufacturers)
}

const getManufactuters = () => {
  sql.query('SELECT * FROM Manufacturer', (error, results) => {
    if (error) console.log(error)
    return results
})

createProducts()

When executing the code above my return is undefined. As I'm using await shouldn't the createProducts function wait for getManufactuters to return to execute the console.log?

obs: I'm using the following npm package: https://www.npmjs.com/package/mysql

CodePudding user response:

Well no, as you're not creating a "Promise" within your function "getManufactuters" (*manufacturers ^^). In fact, your method "getManufactuters" is not async and is just using a callback... To get what you want, rewrite the function to this:

const getManufactuters = () => {
  return new Promise((resolve, reject) => {
    sql.query("SELECT * FROM Manufacturer", (error, results) => {
      if (error) {
        reject(error)
        return
      }
      resolve(results);
    });
  });  
};

Refactored to this, it will be a "Promise" now which can be awaited!

try {
  const manufacturers = await getManufactuters(); // will work now
} catch (e) {
  console.log(e);
}

// and this is basically the same...
getManufactuters().then(result => console.log(result)).catch(error => console.log(error))

You need to know that Promise was there first - that was the original way to call something "asynchronous" in javascript and we ended up with all these callbacks "then.then.then" (also known as callback-hell)

Nowadays we have the two very nice keywords "async" and "await". But the basics haven't changed - you can only await a "Promise". But if something doesn't return a Promise, you won't get an error either - funny right? Javascript just "resolves" it immediately, leaving you alone with no result as you experienced in your example.

So, you cannot throw an "await" to just anything which is not returning a Promise. But cool thing is - you can rewrite anything to be a Promise like shown here ;-)

IF something is already implemented completely with "async/await", then it would work... But then the "sql.query" Function should already be implemented in that way (which is not the case). You can always smell that whenever a function is taking a "callback" parameter -> then it's not a Promise ;-)

  • Related