简体   繁体   English

在继续之前需要等待循环完成执行的可能性有哪些

[英]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 :我有一个简单的 for 循环,如下所示:

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如果你从不让 jfriend 知道你正在使用什么数据库,这里有一些应该工作的东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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