【问题标题】:async function giving await only valid in async function异步函数给等待仅在异步函数中有效
【发布时间】:2019-03-09 17:40:05
【问题描述】:

我正在尝试使计算聚合等待承诺在获取记录中解决。但我无法等待工作。似乎可以做一个then。但我无法让它与 await 一起工作。

我也尝试将它包装在一个承诺中。但没有变化。

我收到错误: await 只在 async 函数中有效

const computeAggregate = async (model, sym) => {
    model.collection.distinct("minutes_offs", {
        symbol: sym
    }, function (error, distMinutes) {
        for (minuteIndex in distMinutes) {
            console.log("inside minutes off", distMinutes[minuteIndex]);
            try {

                const records = await fetchRecords(model, sym, distMinutes[minuteIndex]); //this does not work.
                const aggData = getAggregateData(records);
                createCollection(aggData);
            } catch (e) {
                console.log("error in computeAggregate", e);
            }
        }
    });
}

const fetchRecords = async (model, sym, minutesOff) => {
    console.log("compute function : input param", sym, minutesOff);
    var query = model.find({
        symbol: sym,
        minutes_offs: minutesOff
    }).sort({
        minutes_offs: +1
    });
    return query.exec();
};

【问题讨论】:

  • 您的function (error, distMinutes) { 不是await 所在的async
  • 当然。异步函数中的函数不是异步的,因为它存在。
  • 你的数据库是什么库?
  • 它是猫鼬并且 exec() 返回一个承诺,所以那里没有问题。

标签: node.js


【解决方案1】:

您对 async / await 的使用不当:

const computeAggregate = (model, sym) => {
    model.collection.distinct("minutes_offs", {
        symbol: sym
    }, async (error, distMinutes) => {  // async is required here
        for (minuteIndex in distMinutes) {
            console.log("inside minutes off", distMinutes[minuteIndex]);
            try {

                const records = await fetchRecords(model, sym, distMinutes[minuteIndex]); //this does not work.
                const aggData = getAggregateData(records);
                createCollection(aggData);
            } catch (e) {
                console.log("error in computeAggregate", e);
            }
        }
    });
}

// async is not required here because you never use await
const fetchRecords = (model, sym, minutesOff) => {
    console.log("compute function : input param", sym, minutesOff);
    var query = model.find({
        symbol: sym,
        minutes_offs: minutesOff
    }).sort({
        minutes_offs: +1
    });
    return query.exec(); // this query.exec() must return a promise
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2019-07-15
    相关资源
    最近更新 更多