简体   繁体   中英

Wait for mysql to finish queries in a for loop before finishing a function in nodeJS

I am trying to run a query to get some data from a table, then use that array of data to get some data from another table to then return it as JSON.

I have been trying for a while but I cannot seem to figure out async and await. Right now it does sort of work but doesn't wait for my second query in the for loop to finish before returning data.

app.get("/get-top-trending", (request, response) => {
    const req = request.query
    let query = 'SELECT Ticker, Mentions FROM trend_data ORDER BY Date DESC, ' + req.by + ' DESC LIMIT 3';
    let returnData = {};

    cryptoDB.query(query, (err, tickers) => {
        if (err) throw err;

        getData(tickers).then(function() {
            response.send(returnData)
        });
    });

    async function getData(tickers) {
        for (let i = 0; i < tickers.length; i++) {
            cryptoDB.query('SELECT HistoricalJSON FROM historical_trend_data WHERE Ticker=? LIMIT 1', [tickers[i]['Ticker']], (err, rows2) => {
                if (err) throw err;
                returnData[tickers[i]['Ticker']] = rows2[0]['HistoricalJSON'];
            });
        }
    }
});

I assume that something has to be done in the getData async function, however I am not particularly sure how to implement a working solution. I have tried promises but they don't seem to work the way that I expect.

Any guidance would be appreciated.

solution

app.get("/get-top-trending", (request, response) => {
    const req = request.query
    let query = 'SELECT Ticker, Mentions FROM trend_data ORDER BY Date DESC, ' + req.by + ' DESC LIMIT 3';

    cryptoDB.query(query, (err, tickers) => {
        if (err) throw err;

        getData(tickers).then(function (returnData) {
            response.send(returnData)
        });
    });

    function getData(tickers) {
        const returnData = {};
        return new Promise((resolve, reject) => {
            for (let i = 0; i < tickers.length; i++) {
                cryptoDB.query('SELECT HistoricalJSON FROM historical_trend_data WHERE Ticker=? LIMIT 1', [tickers[i]['Ticker']], (err, rows2) => {
                    if (err) reject(err);
                    returnData[tickers[i]['Ticker']] = rows2[0]['HistoricalJSON'];
                });
            }
            resolve(returnData);
        })

    }
});

async function is not actually wrapping

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