0

I'm playing around something like this

myFunc(){
   new Promise(function(resolve,reject){
    setTimeout(function(){
      //
      resolve();
     },1000)
    })
   .then(function(){
      this.a = 10;
    });
   console.log(this.a)
}

I want to update the vue data property a inside a nested function. What's wrong here ? Note that I cann't use arrow function here for some reason.

Fiddle link: https://jsfiddle.net/bkvcy6j2/

Osman Rafi
  • 938
  • 1
  • 16
  • 37
  • 1
    `.then(() => {this.a = 10;});` or `.then(function(){this.a = 10;}.bind(this));` but in both cases the Promise is async so this.a wont be updated before you console log it – Lawrence Cherone May 20 '21 at 14:31

1 Answers1

1

The reason this doesn't work is because this in then is no the vue.$el. The best way would be do use Arrow Fn.

myFunc() {
  new Promise((resolve,reject) => {
    setTimeout(() => {
      //
      resolve();
     },1000)
   })
  .then(() => {
    this.a = 10;
    console.log(self.a) // here logs 10
  });
  console.log(this.a) // here logs null
}

If you can't use Arrow Fn assign this to variable:

myFunc() {
  const self = this
  new Promise(function(resolve,reject){
    setTimeout(function(){
      //
      resolve();
     },1000)
   })
  .then(function(){
    self.a = 10;
  });
  console.log(self.a)
}
Adam Orłowski
  • 4,268
  • 24
  • 33