简体   繁体   中英

Node.js how to know when all async functions are done?

This is my function:

var Tick = () => {
    binance.prices((error, ticker) => {
        for (var key in ticker) {
            if(key.includes('BTC')) {
                // Cryptocurrency can be bought with BTC
                var currency = {
                    price: ticker[key],
                    symbol: key
                }
                tickerModule.getOne(currency, function(err, rows) {
                    if (err) return console.log(err);
                });
            }
        }
        console.log('done?');
    });
}

I would expect that the console.log would execute after the async function inside but unfortunatly this isn't the case. How can I know when all async functions inside this function are done?

I've been struggling with this issue for a few days now, I hope someone can help me out with this.

Edit: I know I can use the callback function that gets triggered after the tickerModule.getOne however I want to know when all the async functions are done, not when 1 of them is done.

var Tick = () => {
    binance.prices((error, ticker) => {
        const promises = [];
        for (var key in ticker) {
            if (key.includes('BTC')) {
                // Cryptocurrency can be bought with BTC
                var currency = {
                    price: ticker[key],
                    symbol: key
                }
                promises.push(
                    new Promise((resolve, reject) => {
                        tickerModule.getOne(currency, function (err, rows) {
                            if (err) reject(err);
                            else resolve();
                        });
                    })
                );
            }
        }
        Promise.all(promises).then(() => {
            console.log('done?');
        }).catch(err => console.log(err));
    });
}

Uses a simple Promise.all to know when all the async calls are complete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM