简体   繁体   中英

What are the possibilities when you need to wait for a loop to finish executing before continuing

I have a simple for loop like the following one :

var array = [];

for (var key in results) {
    con.query('SELECT * FROM table WHERE id = ?', [results[key]], function (err, res, fie) {
        array.push(res);
    });
}

res.json({result: array});

The code in the loop takes time to execute so the result is sent before the loop has time to finish and therefore the value of my array is incorrect.

I looked it up but couldn't find a proper response to this case. I wanted to know what were the possibilities I had for my code to wait for the loop to completely execute before continuing ?

Thanks, any help much appreciated

In case you never let jfriend know what database you are using, here's something that should work

// a "promisified" con.query ... though, not sure what the `fie` argument is
// as it's not used, it wont matter

const queryP = (sql, ...args) => 
    new Promise((resolve, reject) => 
        con.query(sql, ...args, (err, res, fie) => 
            err ? reject(err) : resolve(res)
        )
    );

Now, your code can be written

results // if results is an Object, use: Object.values(results) instead
.map(result => queryP('SELECT * FROM table WHERE id = ?', result))
.then(result => res.json({result}));

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