【问题标题】:Stuck in asnyc/await陷入异步/等待
【发布时间】:2018-09-30 01:07:07
【问题描述】:

搜索了很多地方,也阅读了很多教程,以深入了解 javascript 的 async/awiat 行为。这是我的代码:

var bookAppointment =  async (data) => {
    return User.findOne({_id: data.user_id})
    .then((userfound) =>{
            //manipulate user's data and find if in array the specific object exist
            var found = await userfound.dataArray.find( function(element){
              return element.data == data.user_data
            });
            //here I want to wait until above result comes to evaulate below condition
            if(found)
            {
                return "Sorry! data does not exist";
            }
            else
            {
                return userfound;
            }
    })
    .catch(err => {
        return err 
    });
} 

我想要实现的是让我的 if else 条件在 javascript 数组上的 find 函数之上等待。这是我面临的错误:

SyntaxError: await is only valid in async function

我无法理解我错在哪里!甚至我的函数也有关键字 async 及其定义。周围有人寻求快速帮助吗?

【问题讨论】:

  • (userfound) =>{...} 你正在定义另一个函数,为了等待工作,你需要它类似于 async (userfound) => {...}
  • (userfound) => {...} 中的整个部分将同步运行,一次一步,为什么要等待.find 方法? .如果您确实想等待,请按照上面的评论。
  • 像魅力一样工作!哈哈 非常感谢!!在我的愚蠢错误上浪费了将近 2 个小时!谢谢指正!

标签: javascript node.js express async-await


【解决方案1】:

(userfound) =>{...},您正在定义另一个函数。

要让 await 工作,您需要它类似于 async (userfound) => {...}

【讨论】:

  • 感谢老兄的帮助!!
【解决方案2】:

不使用 Catch 和 Then 关键字的是 async/await 函数。

    var bookAppointment = async (data) => {
      var found = await User.findOne({_id: data.user_id});
      try {
      //do here like in then
      } catch (e) {
      //error handling
      }
    }

【讨论】:

  • 这在几个方面是错误的。首先,try/catch 必须在 try 块内有 await User.findOne() 才能发挥作用。而且,您可以根据需要将.then()await 结合使用。它会工作得很好。
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 2021-08-12
  • 2016-07-07
  • 2016-03-25
  • 2017-10-09
  • 2021-10-22
相关资源
最近更新 更多