VueJS异步等待 - regeneratorRuntime未定义

3

我正在尝试在我的应用程序中注册一个新用户,但无法有效地检查用户名是否存在 - 更准确地说,“检查”会被“点击”延迟..

这是我的组件:

<template lang="html">
  <div class="main">
    <tw-navbar></tw-navbar>

    <div class="container-fluid">
     <div class="row">
       <tw-sidebar></tw-sidebar>

         <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-md-4">
          <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3">
            <div class="container">
              <h1 class="h2">Add new customer</h1>
              <form class="w-50 m-auto">
              <div class="form-group">
                <label for="username">Username</label>
                <input type="username" class="form-control" id="username" placeholder="Enter username"
                        v-model.lazy="customerData.username">
              </div>
              <button type="submit" class="btn btn-primary" @click.prevent="addUser">Add</button>
            </form>
            </div>
          </div>
         </main>
     </div>
    </div>
  </div>
</template>

组件内的脚本
<script>
  import Navbar from './../navigation/Navbar.vue'
  import Sidebar from './../navigation/Sidebar.vue'
  import CustomerService from './../../services/CustomerService'
  import { EyeIcon, EyeOffIcon } from 'vue-feather-icons'

  export default {
      data() {
        return {
          customerData: {
                          username: '',
                        },
          usernameExists: null,
        }
      },
      methods: {
        addUser(){
            console.log("Before: "+this.usernameExists)

             CustomerService.checkUserExists(this.customerData.username)
                 .then(response => {
                  this.usernameExists = response.data['0'].exists
                  console.log("Inside: "+this.usernameExists)
                })
                .catch(e => console.log(e))

            console.log("After: "+this.usernameExists)
        },

      },
      components: {
        'tw-navbar': Navbar,
        'tw-sidebar': Sidebar,
        EyeIcon,
        EyeOffIcon
      }
    }
</script>

<style lang="css" scoped>
</style>

客户服务仅调用API,该API根据数据库查询返回1(=存在)或O(=可用)(=> SELECT count(*) as exists FROM users WHERE username = $1)。

API(BE)本身运行得非常完美。

问题在于前端没有等待API响应,因此出现了“一次点击”延迟的情况。

当我点击添加用户按钮时,控制台会给我输出以下内容:

Before: null
After: null
Inside: 1

当我再次点击ADD按钮时...它会给我(延迟)正确的结果:
Before: 1
After: 1
Inside: 1

当然,如果我修改了用户名(为一些不存在的名称):
Before: 1
After: 1
Inside: 0

在内部,它返回用户名可用,但在应用程序中似乎该用户名已被使用(这是错误的)

所以你可以看到,内部运作良好,问题在于它被最后一个调用..

我应该实现ASYNC / AWAIT - 但这就是我的困境..有人能帮帮我吗?通过建议需要进行的代码更改?非常感谢


这个回答解决了你的问题吗?Babel 6 regeneratorRuntime is not defined - aRvi
不是很确定... 不知道如何在VueJS组件中实现它.. 你能分享一个样例代码吗? - Mr.P
3个回答

3

只需安装core-jsregenerator-runtime,并在主入口文件的开头导入即可。

npm i -S core-js@latest regenerator-runtime@latest

在我的情况下,我将main.js文件添加到了Webpack的entry键中,因为它是我的主要入口文件。
// this is a recommendation of babeljs (https://babeljs.io/docs/en/babel-polyfill)
// because @babel/polifill is deprecated
import 'core-js/stable'; 
import 'regenerator-runtime/runtime';

// also is possible
// import 'core-js'; 
// import 'regenerator-runtime';
...
// other imports

我希望这会对你有所帮助。 祝好。


0

简单解决方案

1.) 运行 npm install regenerator-runtime

2.) 在你的 webpack 入口文件(通常是 app.js 或 main.js)中添加 import 'regenerator-runtime';


0

好的,我弄明白了...当时我只是不理解async/await或promise链 :)

所以答案非常简单:

AsyncAwait解决方案:

async addUser(){
        console.log("Before: ")

        const isUnique = await CustomerService.checkUserExists(this.customerData.username)
        if(!isUnique) throw new Error("Oops already exists")    

        console.log("After: ")
    },

Promise 链接:

addUser(){
        console.log("Before: ")

        CustomerService.checkUserExists(this.customerData.username)
           .then(data => {
                if(!data.isUnique) throw new Error("Oops already exists")
                console.log("After: ") 
                return //-- go to another then() section -> continue in the promise chain
           })
           .then(() => {
                console.log("After the after :)")
                return //-- go to another then() section -> continue in the promise chain
           })
           .then(() => {
                console.log("After the after-after :)")
           })
           .catch(error => {
                 console.log("Error:",error)
           })
           
    },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接