Uncaught SyntaxError: await is only valid in async function

文章目录

    在使用 sweet alert 组件时,遇到一个错误提示:

    Uncaught SyntaxError: await is only valid in async function

    function edit_dis_top(user_id) {
      const {value: formValues} = await Swal.fire({
          title: '设置推荐人',
          // ...
      })
    
      if (formValues) {
          Swal.fire(JSON.stringify(formValues))
      }
    }
    

    这让我想起了 C# 的 await 关键字。。。

    Async 有什么用?

    从内部写法看,await 提供了异步操作的同步写法。

    await consumes promise/future/task-returning methods/functions and async marks a method/function as capable of using await. Await is actually doing the same process of promise/resolve and as the function is async other task is processing in a parallel way

    解决方法是:

    在 function 前加上 async 关键字。

    async function edit_dis_top(user_id) {
      const {value: formValues} = await Swal.fire({
          title: '设置推荐人',
          // ...
      })
    
      if (formValues) {
          Swal.fire(JSON.stringify(formValues))
      }
    }