我正在尝试让计算聚合器等待承诺在获取记录中解析。但是我无法等待工作。似乎有可能再做一次。但是我无法使其与await一起使用。
我也试图将其包装在一个诺言中。但是没有变化。
我遇到了错误: 等待仅在异步功能中有效
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();
};
答案 0 :(得分:0)
您对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
};