【问题标题】:The code is not executed async even after adding async/await即使添加了 async/await,代码也不会异步执行
【发布时间】:2021-04-18 07:21:57
【问题描述】:

在以下代码中:

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);

get 函数:

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 打印出正确的值。

【问题讨论】:

  • 如何调用 getIVoneDay() ?
  • "这三个函数接受一些参数,在数据库中进行查询并返回一个需要一点时间的值。" 他们返回一个承诺还是只接受一个打回来?请参阅How do I convert an existing callback API to promises?,尽管您的 API 可能已经支持替代的 Promise 接口。
  • 似乎您需要更深入地了解您的函数并检查它们返回未定义的原因。将日志放入其中并检查,可能是您的数据库返回 undefined 而原因不在 async/await 中
  • @Alex 请检查编辑。
  • getPE 没有返回任何内容。它应该返回一个Promise(参见@VLAZ 评论)

标签: javascript asynchronous async-await async.js


【解决方案1】:

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

【讨论】:

  • 我也试过了,但没用。我得到了同样的结果。
【解决方案2】:

更改 get 函数,如以下代码,因为它不是 async 函数:

let getPE = async (symbol, option, date, exp_date, strike) => {
  var collection_pe = symbol + ".PE";
  var model_pe = mongoose.model("model_pe", bhavcopySchema, collection_pe);
  // Return the promise
  try {
    let result = await model_pe.find({
      SYMBOL: symbol,
      STRIKE_PR: strike,
      OPTION_TYP: "PE",
      EXPIRY_DT: new Date(exp_date),
      TIMESTAMP: new Date(date),
    })
    let close_pe = result[0].CLOSE.value;
      console.log(close_pe);
      return close_pe;
  } catch (error) {
    throw error
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2015-11-02
    • 2018-12-15
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    相关资源
    最近更新 更多