0

I'm learning Vue.js right now and wanted to test out async await function using Vue instance.

I found weird bug where assigned data (number in this case) will result as 'undefined' when async await is triggered. Can anyone explain why this behavior is happening? Thanks.

<body>

<div id='wrapper'>
    <div>{{ num }}</div>
    <button @click='triggerr()'>{{ c }}</button>
</div>
<script>

new Vue({
    el: '#wrapper',
    data: {
        num: 5,
        c: 'click'
    },
    methods: {
        settt(){
            console.log(this.num);                                    //outputs 5 (expected)
            let abc = setInterval(()=>{
                console.log(this.num);                                //outputs undefined (????)
                this.num--;
                if (this.num === 0){
                    clearInterval(abc);
                    return new Promise(function(res, rej){
                        res('Done!');
                    });
                }
            }, 1000);
        },
        async triggerr(){
            let result = await this.settt();
            this.num = result;
        }
    }
});

This is the full code if you want to see the error: https://www.w3schools.com/code/tryit.asp?filename=GHBBMXS1AR7P Demo of what it's suppose to do: https://www.w3schools.com/code/tryit.asp?filename=GHBBPY9BFK60

passionateLearner
  • 722
  • 1
  • 7
  • 19
  • 1
    You aren't returning the promise from `settt`, you're returning it from the `setInterval` arrow function. – skirtle Aug 01 '20 at 07:10
  • @skirtle @str The linked question answers only 1 part of the problem which is handling `async-await` but does not solve it within the context of vuejs. For example in this specific question OP can't use arrow functions since the context of `this` won't be set correctly. – painotpi Aug 01 '20 at 07:16
  • 2
    @pai.not.pi The problem is that the `settt` function does not return anything, instead it should return a promise. Whether it is in the context of Vue.js or not does not make a difference. The arrow function is the correct way to *retain* the correct this context. – str Aug 01 '20 at 07:18
  • @str Cool, fair enough. – painotpi Aug 01 '20 at 07:21

0 Answers0