0

I am new to NodeJS with MySQL Database and I want to execute my code for nested queries. The scenario is that I have to get the list of incomplete trades and then by using iterative loop to iterate the list which I have received from database. In the loop there are more queries executing and a 3rd party API is called to fetch the data which returns data in a callback. Now the issue is that callback execute asynchronously and the loop doesnt wait for the callback to return data and it moves on. Kindly guide me as I am stucked in this situation.

Here is my code

var sql = incompleteTradesQuery.getIncompleteTrades();
    sqlConn.query(sql, function (err, data) {
        if (err) {
            console.log(err);
        }
        else {
            for (var i = 0; i < data.length; i++) {
                bittrexExchange.getOrder(data.order_uuid, function(err, order_data) {
                if (order_data.result.IsOpen != true) {
                var order_sql = tradesQuery.insertTrade(order_data.result.OrderUuid, order_data.result.Exchange, data.customer_id, order_data.result.Quantity, order_data.result.QuantityRemaining, order_data.result.Limit, order_data.result.Reserved, order_data.result.ReserveRemaining, order_data.result.CommissionReserved, order_data.result.CommissionReserveRemaining, order_data.result.CommissionPaid, order_data.result.Price, order_data.result.PricePerUnit, order_data.result.Opened, order_data.result.Closed, order_data.result.IsOpen, null, data.commission_fee, data.total_transfer, new Date());
                sqlConn.query(order_sql);

                var incomplete_trades_query = incompleteTradesQuery.deleteIncompleteTradesById(data.id);
                sqlConn(incomplete_trades_query);
             }
           });
            }
        }
    });
ALI Sajjad Rizvi
  • 185
  • 5
  • 20
  • 1
    Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Brahma Dev Oct 05 '17 at 09:28

1 Answers1

2

Since, NodeJS fundamentally works in asynchronous nature, your nested queries will also be asynchronous and it will be a painful task to write chain of callbacks. One simple answer to your question will be use promises.

Additionally, I would recommend you using asynchronous way to handle your multiple queries which will undoubtably, work faster than the synchronous way of handling queries/requests.

NodeJS also provides async.js module that will solve your problem. Q and Step are also good packages to handle your nested callback code.

https://code.tutsplus.com/tutorials/managing-the-asynchronous-nature-of-nodejs--net-36183