javascript - 即使添加了 async/await,代码也不会异步执行
问题描述
在以下代码中:
let getIVoneDay = async (symbol, option, date, exp_date, strike) => {
let close_ce = await getCE(symbol, option, date, exp_date, strike);
const close_pe=await getPE(symbol, option, date, exp_date, strike);
const close_xx= await getXX(symbol, option, date, exp_date, strike);
console.log(close_ce,close_pe,close_xx);
};
我得到了价值
undefined undefined undefined
这三个函数需要一些参数,在数据库中进行查询并返回一个需要一点时间的值。所以,我尝试将它与 async/await 一起使用,但我得到了相同的结果。我怎样才能做到这一点?我也尝试过同样的回调并得到相同的结果。
调用:
var x = getIVoneDay("ACC", "CE", "2020-01-01", "2020-01-30", 1220);
获取函数:
let getPE = (symbol, option, date, exp_date, strike) => {
var collection_pe = symbol + ".PE";
var model_pe = mongoose.model("model_pe", bhavcopySchema, collection_pe);
model_pe
.find({
SYMBOL: symbol,
STRIKE_PR: strike,
OPTION_TYP: "PE",
EXPIRY_DT: new Date(exp_date),
TIMESTAMP: new Date(date),
})
.exec((err, result) => {
let close_pe = result[0].CLOSE.value;
console.log(close_pe);
return close_pe;
});
};
PS:getCE() 和其他函数中的 print 打印出正确的值。
解决方案
您的函数getPE()
实际上不是异步函数。没有返回值。
您应该更改它以返回如下承诺:
let getPE = (symbol, option, date, exp_date, strike) => {
var collection_pe = symbol + ".PE";
var model_pe = mongoose.model("model_pe", bhavcopySchema, collection_pe);
// Return the promise
return model_pe
.find({
SYMBOL: symbol,
STRIKE_PR: strike,
OPTION_TYP: "PE",
EXPIRY_DT: new Date(exp_date),
TIMESTAMP: new Date(date),
})
.exec((err, result) => {
let close_pe = result[0].CLOSE.value;
console.log(close_pe);
return close_pe;
});
};
推荐阅读
- javascript - 在用户生成的多维数组中选择项目,整列被选中
- python-3.x - 如何更改 numpy.ndarray 的形状?
- c# - ASP.NET Core MVC - Razor - asp-action 路由问题
- javascript - 画布上的字体被拉伸并压扁
- python - 如何使用 python 模拟 websocket 请求并捕获流数据?
- r - 在 grepl 之后将字符串分成新行
- windows - Powershell 替换 vs sed
- amazon-web-services - [serverless-framework]将应用程序部署到新阶段尝试更新旧阶段
- swiftui - ScrollView 文本对齐 SwiftUI
- r - 为轴刻度上的数字添加后缀?