0

i have object array results from parallel asynchronus callback, the next process i want to insert my objact array results to my table using looping for, but i dont now to handle my status insert.

var boolean = false;

  if(results.code.success === true){
    for(i=0; i<req.body.id_barang.length; i++){
      detail[i] = {
        "id_transaksi" : results.code.id_transaksi,
        "id_barang" : req.body.id_barang[i],
        "qty" : req.body.qty[i],
        "sub_total" : parseInt(req.body.sub_total[i].replace(/,.*|\D/g,''),10)
      }
      connection.query("insert into detail_transaksi set ? ", detail[i], function(err, rows){
        if(err){
          null
        } else{
          boolean = true;
        }
      })
    }
  }
  var output = {"success" : boolean}
  res.send(output);
aeeeeeeng
  • 23
  • 3
  • 1
    You need to learn a lot about asynchronous operations in node.js and their timing. Async callbacks happen sometime in the future. Meanwhile, you are sending the output before any of them have completed. – jfriend00 Jul 28 '17 at 02:45

1 Answers1

0

To expand on jfriend00's answer, function(err, rows) is a callback function that will execute once the query is resolved. Meanwhile, rather than waiting for the query to resolve, var output = {"success" : boolean} will be executed without the boolean modification in the callback.

So, in order to properly send the output, you must include your code in the callback, after boolean = true;.

Here's a great question giving a basic example of callback usage in node.js.

William Armiros
  • 267
  • 1
  • 10