0

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.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Does this answer your question? [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) – Heiko Theißen Jan 14 '23 at 11:00
  • You are mixing synchron code with asynchron code execution. – Marc Jan 14 '23 at 13:40

1 Answers1

0

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)
Andrey Smolko
  • 712
  • 3
  • 8