0

I am developing an application with vuejs. I want to use this inside a promise, I want to be able to call a function or data inside the .then scope, and for that I use the this. But if I do this inside the .then I get an error, it seems this to be lost even though I bind the scope with and arrow function. What can I do?

javascript
  methods: {
    ...mapActions(['setCredentials']),
    doLogin() {
      console.log('credentials ' + this.username, this.password);
      this.$store.dispatch('connect', {
        username: this.username,
        password: this.password,
      });

      this.checkResult().then((interval) =>  {
        vm.$f7router.navigate('/favorites');

      })

},
    checkResult() {
    return new Promise(function(resolve) {

        var id = setInterval( () => {
                let condition = this.$store.state.isConnected
                   if (condition) {
                    clearInterval(id);
                    resolve(id);
                }

            setTimeout(() => {
                clearInterval(id);
                reject(id);
            }, 20000);
        }, 10);
    });
}
Rasim Avcı
  • 1,123
  • 2
  • 10
  • 16

3 Answers3

2

Use arrow function when instanciating your promise:

return new Promise((resolve) => { /* ... */ });
Faly
  • 13,291
  • 2
  • 19
  • 37
1

The error is due to the context binding. You can use Arrow function as they have no this property of their own (They rely on their parent function's this property).

Change return new Promise(function(resolve) {..

to return new Promise((resolve) => {..

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
1

Try to create a var before the promise like: var self = this; then use self instead of this inside the promise

  • thanks but this time I have problem for setTimout. gives undefined erro for reject inside setTimout even if I use arrow function , use that.reject, or solely this.reject – Rasim Avcı May 22 '18 at 08:34
  • I see I need to define reject with resolve in function signature, thanks. – Rasim Avcı May 22 '18 at 09:14