for循环不尊重等待

时间:2018-02-04 01:01:26

标签: javascript asynchronous async-await

所以我有以下代码:

const getHourlyData = async(size, callback) => {

  for (var i = size; i > 0; i--) {
    const candle = await internals.getData(x, y, i, (result) => {
       resultSet.push(result);
    });
  }
  callback(null, resultSet);
}

然而for循环不等待,它总是用空值填充数组。 getData函数如下所示:

(x, y, i, callback) => {
    //...
    const result = pool.query(query, (error, results, fields) => {
        if (error) {
          console.log(error);
        }
        callback(results);
    });
  }

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

看起来你想要像这样建立你的系统:

fn = async () => 1
fn2 = async () => await fn()
await fn2()
// result is 1

阅读本文并考虑迁移到async / await架构: https://medium.freecodecamp.org/javascript-from-callbacks-to-async-await-1cc090ddad99