最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asynchronous - Javascript - async await doesn't work with conditional - Stack Overflow

programmeradmin6浏览0评论

I've been working on it for several hours and I'm still more and more confused about how async/await works. Right now I have this code:

    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;
            });
        },
    }

My goal is simple - if method checkIfUniqueEmail() returns true I want to see console.log and will emit change-state. The problem is that constant uniqueEmail is always undefined. How can I make this only after response from function checkIfUniqueEmail() is true? What I need to change? I'm using vue.js 2.1.10.

I've been working on it for several hours and I'm still more and more confused about how async/await works. Right now I have this code:

    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;
            });
        },
    }

My goal is simple - if method checkIfUniqueEmail() returns true I want to see console.log and will emit change-state. The problem is that constant uniqueEmail is always undefined. How can I make this only after response from function checkIfUniqueEmail() is true? What I need to change? I'm using vue.js 2.1.10.

Share Improve this question asked Jan 12, 2018 at 14:43 Jaroslav KlimčíkJaroslav Klimčík 4,84813 gold badges41 silver badges60 bronze badges 2
  • checkIfUniqueEmail needs to be an async function to be able to use it along with await. docs – Adelin Commented Jan 12, 2018 at 14:45
  • Uh, your checkIfUniqueEmail method doesn't return the promise - returning inside the then callback alone is not enough – Bergi Commented Jan 12, 2018 at 14:46
Add a ment  | 

2 Answers 2

Reset to default 2

You need to make your method return the promise

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;
    });
}

Consider this:

    async function validateFields() {
      var uniqueEmail = await checkIfUniqueEmail();
        if(uniqueEmail) {
          console.log('uniqueEmail is true'); 
        }  
    }
    
    function checkIfUniqueEmail(){
      return new Promise(resolve => {
      	setTimeout(() => {
          resolve('[email protected]');
        }, 1000)
      })
    }
    
    validateFields();

The above, actually represents your situation, so considering this simple example it is clear that simply returning a resolved Promise is a possible way to go. So you can just do something like:

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)
        };
    }
<...>
发布评论

评论列表(0)

  1. 暂无评论