0

I am trying to make the compute Aggregate to wait for the promise to resolve in fetch records. But I can't get the await to work. It seems possible to do a then. But I can't get it to work with await.

I also tried to wrap it in a promise. But no change.

I am getting the error: await is only valid in async function

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();
};
user2130951
  • 2,601
  • 4
  • 31
  • 58

1 Answers1

0

You make a bad usage of 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
};
dun32
  • 708
  • 6
  • 9