首页 > 解决方案 > 即使添加了 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 打印出正确的值。

标签: javascriptasynchronousasync-awaitasync.js

解决方案


您的函数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;
    });
};

推荐阅读