给出 await 的异步函数仅在异步函数中有效

用户2130951

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

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

我收到错误:等待仅在异步函数中有效

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();
};
邓32

您对 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
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章