Sarus Crane
Sarus Crane

Reputation: 336

how can call another function after excuted multiple function in loop node js

Please find below code

function get_btc(address) {

    address_transaction(address, user_id, coin_key, deposite_txn_fee, function(callback) {

        for (var j = 0; j < callback.response.data.txs.length; j++) {
            let user_id = callback.user_id;

            //some code//
        }
    });
}

get_label_info(function(err, data) {

    for (var i = 0; i < data.length; i++) {

        let address = data[i].address;

        deposite_model.get_coin_info(function(err, data1) {

            var coin_name = data1[0].coin_code;

            const return_functions = get_switch(coin_name);

            if (return_functions) {

                obj[return_functions](address);
            }
        })
    }
});


function all_completed() {
    console.log('all functions has been completed');
}

By the help of above mentioned code i want to excecute all_completed loop when all functions has been completly done.
At the initial start get_label_info function is excuted then controller go on to get_btc function.

Please help me how could i run all_completed functions after all functions completed run.

Upvotes: 1

Views: 44

Answers (1)

vicatcu
vicatcu

Reputation: 5837

I'll assume you are using es6, and that you know what a Promise is in that context. In that case wrap all your callback based things in a Promise that resolves when the callback completes. Then, in your loop, push all your Promises into an array variable. Finally call Promise.all with that array as an argument and call then on the result to encapsulate the code you want ti run after they all complete (resolve).

Upvotes: 1

Related Questions