【问题标题】:Javascript - async await doesn't work with conditionalJavascript - 异步等待不适用于条件
【发布时间】:2018-06-22 01:10:55
【问题描述】:

我已经为此工作了几个小时,但我仍然对 async/await 的工作原理越来越感到困惑。现在我有这个代码:

    created: function () {

         Event.$on('open-stage', (stage) => {

            this.$validator.validateAll().then(() => {

                const validateFields = async () => {
                    const uniqueEmail = await this.checkIfUniqueEmail();
                    if(uniqueEmail) {
                       console.log('uniqueEmail is true'); // <-- this is what I need to achieve
                       Event.$emit('change-stage', this.wizardStage.successor);
                    }
                };

                validateFields();
            }).catch(() => {
                toastr.warning('Error');
                Event.$emit('change-stage-denied');
                return true;
            });
        });
    },

    methods: {
        checkIfUniqueEmail() {
            if (!this.player.email || !this.player.email.length) {
                return true;
            }

            this.$http.post('playerExists', {
                email: this.player.email
            }).then(response => {
                if (response.data.exists) {
                    toastr.error(Good');
                    Event.$emit('change-stage-denied');
                    return false;
                }
                return true;
            }).catch(error => {
                toastr.warning('Fail');
                Event.$emit('change-stage-denied');
                return false;
            });
        },
    }

我的目标很简单 - 如果方法 checkIfUniqueEmail() 返回 true,我想查看 console.log 并将发出 change-state。问题是常量uniqueEmail 始终未定义。只有在函数checkIfUniqueEmail() 的响应为真后,我才能做到这一点?我需要改变什么?我正在使用 vue.js 2.1.10。

【问题讨论】:

  • checkIfUniqueEmail 必须是async 函数才能与await 一起使用。 docs
  • 呃,你的 checkIfUniqueEmail 方法没有 return 承诺 - 仅在 then 回调中返回是不够的

标签: javascript asynchronous vue.js async-await vuejs2


【解决方案1】:

你需要让你的方法返回承诺

checkIfUniqueEmail() {
    if (!this.player.email || !this.player.email.length) {
        return true;
    }

    return this.$http.post('playerExists', {
        email: this.player.email
    }).then(response => {
        if (response.data.exists) {
            toastr.error('Good');
            Event.$emit('change-stage-denied');
            return false;
        }
        return true;
    }).catch(error => {
        toastr.warning('Fail');
        Event.$emit('change-stage-denied');
        return false;
    });
}

【讨论】:

  • 不,你不需要需要做到async——返回承诺就足够了。但是当你这样做时,你可能应该放弃thencatch 并正确使用await
【解决方案2】:

考虑一下:

    async function validateFields() {
      var uniqueEmail = await checkIfUniqueEmail();
        if(uniqueEmail) {
          console.log('uniqueEmail is true'); 
        }  
    }
    
    function checkIfUniqueEmail(){
      return new Promise(resolve => {
      	setTimeout(() => {
          resolve('johny@bravo.com');
        }, 1000)
      })
    }
    
    validateFields();

以上内容实际上代表了您的情况,因此考虑到这个简单的示例,很明显简单地返回已解决的 Promise 是一种可能的方式。所以你可以这样做:

this.$http.post('playerExists', {
    email: this.player.email
}).then(response => {
    if (response.data.exists) {
        toastr.error('Good');
        Event.$emit('change-stage-denied');
        return new Promise(resolve => {
           resolve(true)
        };
    }
<...>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2020-03-31
    相关资源
    最近更新 更多