Home > Back-end >  Node.js return result/error from mysql conn.query
Node.js return result/error from mysql conn.query

Time:01-16

I hope anyone can help me. I tried to invoke the function createProduct and create a new dataset in my MySQL database. But I want to return the error/result.

let sql = "INSERT INTO ZUTAT (ZUTATENNR, BEZEICHNUNG, EINHEIT, NETTOPREIS, BESTAND, LIEFERANT, KALORIEN, KOHLENHYDRATE, PROTEIN, Gelistet, Bild) VALUES ?";
let values = [
  [data.pNr, data.pName, data.pUnit, data.pPrice, data.pCount, '101', data.pKa, data.pKo, data.pPr, data.pListed, data.pImage]
];
let output;

con.query(sql, [values], function(err, result) {

  if (err) {
    console.log('Error: '   err);
    returnBack(err);
  } else {
    console.log('Result: '   result);
    returnBack(result);
  }
});

function returnBack(returnValue) {
  console.log('Return: '   returnValue);
  output = returnValue;
}

l().then({
  function() {
    console.log('t: '   output);
    return output;
  }
})
}

The problem is that the return statement executes before the con.query does. I tried async but it doesn't works.

CodePudding user response:

if O want to return value from createProduct I would do smth like that:

let createProduct = async function(data) {

  let sql = "...";
  let values = [...]

  return new Promise((res, rej)=>{
   con.query(sql, [values], function (err, result) {
     if (err) {
        console.log('Error: '   err);
        rej(err);
     } else {
        console.log('Result: '   result);
        res(result);
     }
  });
  }
}

// later in the code (inside async function)
let result = await createProduct(data);
console.log(result)
  • Related