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);
             }
           });
            }
        }
    });
1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

can you provide me the code snippet for how to use it in my own code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.