陷入asnyc / await

时间:2018-04-19 13:40:06

标签: javascript node.js express async-await

在许多地方进行了搜索,并通过了许多教程来深入了解javascript的异步/ 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数组查找函数。这是我面临的错误:

SyntaxError: await is only valid in async function

我无法理解我错在哪里!甚至我的函数也有与其定义的关键字异步。周围有人可以快速帮忙吗?

2 个答案:

答案 0 :(得分:1)

(userfound) =>{...}您正在寻找其他功能。

等待工作,你需要它像async (userfound) => {...}

答案 1 :(得分:-1)

未使用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
      }
    }