0

I have been struggling for a few days with a problem that seems simple to me. I want to insert a value if it does not exist in a mysql database with nodejs. I have an array of array, and I need to loop inside a child to check every data.

Example of data

finalRow = [['a > 'b'], ['a' > 'c']];

My code

    for(let i=0; i < finalRow.length-1; i++) {

      var splitcat = finalRow[i].split(' > ');

      (async function(){
        for(let j=0; splitcat.length-1; j++) {
          var query = "SELECT * from category where name = '" + splitcat[j] + "'";
              await con.query(query, async function (err, result, fields) {

              if (err) throw err;
              if(result && result.length) {
                console.log("nothing");
              } else {
                 console.log("insert into db");
                await con.query(`INSERT INTO category (name, url, description, parent_id) VALUES (?, ?, ?, ?)`,
                          [splitcat[j], '', '', null], function (err, result) {
                          if (err) throw err;
                });

              }
            });
        }
      })();

I tried several versions of this code, but the loop does not wait for the existence check and inserts all the data. Thanks for your help

RubenSmn
  • 4,091
  • 2
  • 5
  • 24
  • using `await` together with the callback form `con.query("...", (err, result, fields) => {})` doesn't make any sense ... Especially it won't work, ie as `con.query()` doesn't return a promise, `await` is a noop and doesn't await anything ... Check if your library supports promises. If yes, use them. If not, use a library that supports promises ... – derpirscher Nov 13 '22 at 17:41
  • 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) – derpirscher Nov 13 '22 at 17:45
  • Hi, I think you right, I tried to log I got an error : "YYou have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, which is a programming error. Try calling con.promise().query(), or require('mysql2/promise') instead of 'mysql2' for a promise-compatible version of the query interface." – Thibaut_MT Nov 13 '22 at 18:32

0 Answers0