嵌套异步等待与循环结合 [英] Nested async await combined with loops

查看:59
本文介绍了嵌套异步等待与循环结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改:这是我的完整代码,没有任何错误:

Edit: Here is my full code that throws no errors:

router.get('/:id/all', async (req, res, next) => {
    let id = req.params.id;
    let t;                         
    let d;                         
    let o;                         
    let p;
    let data = [];
    let entry = {};
    try {
        let rowConfig = await methods.runQuery('SELECT SystemID, Begin, End, Power FROM Configuration WHERE ID = ?', id);
        p = rowConfig[0].Power;
        let begin = rowConfig[0].Begin;
        let end = rowConfig[0].End;
        let counter = [Var1, Var2, Var3];
        
        let result = await methods.runQuery('SELECT * FROM Table1 WHERE ID = ?', id);
        result.forEach(async function(row) {
            let resultT;
            if (!row.EventStop) {
                t = row.EventBegin - begin;
                resultT = await methods.runQuery('SELECT EventBegin, EventStop FROM Table1 WHERE ID = ? AND RootID IN (4, 5) AND IsValid = TRUE AND EventBegin < ?', [id, row.EventBegin]);
            }
            else {
                t = row.EventStop - begin;
                resultT = await methods.runQuery('SELECT EventBegin, EventStop FROM Table1 WHERE ID = ? AND RootID IN (4, 5) AND IsValid = TRUE AND EventBegin < ?', [id, row.EventStop]);
            }
            console.log(t);
            d = 0;
            resultT.forEach(function(row) {
                let dt = row.EventStop - row.EventBegin;
                d = d + dt;
            });
            o = t - d;
            console.log(o);
            entry = {'1': t, '2':o};
            data.push({entry});
        });
    } 
    catch (error) {
        res.status(500).send({ error: true, message: 'Error' });
    }
    return res.send({ data: data });
});

但是发送的数据数组仍然为空!所以我看了看我的控制台,看到两个突出.

But the data array that is sent remains emtpy! So i looked in my console and two stand out.

  1. t o 的值错误
  2. 当get方法已经确定时,他们会在控制台中登录.因此,当发送数据数组时,显然其中没有任何条目.

代码执行顺序:

对于Table1的每一行,我要具有 t o ,因此应该是:

For each row of Table1 i want to have t and o, so it should be:

forEach循环(第1行)

forEach loop (row1)

-> if/else->计算t

-> if/else -> calculate t

->获取resultT

-> get resultT

-> forEach循环(第1行)

-> forEach loop (row1)

->计算d

-> forEach循环(row2)

-> forEach loop (row2)

->计算d

-> ...

->计算o

->将条目推送到数据

-> forEach循环(第2行)

-> forEach loop (row2)

-> ...

我正在使用node并表示要创建Rest API.由于节点的异步行为,我目前正在苦苦挣扎.这是我要实现的目标:

I am working with node and express for creating a Rest API. I am currently struggling because of the asynchronous behaviour of node. This is what I am trying to achieve:

在get方法中,我想从数据库中收集表的所有数据.

In a get method, I want to collect all the data of table from my database.

router.get('/:id/all', async (req, res, next) => {
...
try {
let result = await methods.runQuery('SELECT SystemID, Begin, End, Power FROM Configuration WHERE ID = ?', id);

runQuery方法如下所示:

The runQuery method looks like this :

module.exports.runQuery = function(sql, parameter){
return new Promise((resolve, reject) => {
    dbConn.query(sql, parameter, function (error, result, fields) {
      if (error) reject(error);
      else {
        resolve(result);
      } 
    });
  });
}

到目前为止,该方法仍然有效.现在我的问题开始了.对于此表的每一行,我想做一些事情.在此for循环中,我需要进行相互依赖的计算.}

This works so far. Now my problems start. For each row of this table I want to do something. Inside this for loop I need to do calculations that depend on each other. }

推荐答案

正如我在评论中提到的, await forEach 循环中不起作用.尝试 for ... of 循环.

As I have mentioned in the comment, await won't work in forEach loop. Try for...of loop instead.

示例:

for (let row of result) {
  // await will work here
}

这篇关于嵌套异步等待与循环结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆