How do I use Vue router inside a promise?

I call a function that posts to the server, the function that posts to the server return a promise resolve/reject and I get this promise in my “postArticle” page. If it’s successful, I will redirect to another page, if not, I will show an error.

This is the function in my postArticle.vue:

articlePublish.sendInfo("savearticle",  info).then(function(this: any, r: any){
            
          if(r.data=="ok"){        
            this.router.replace("/Blog");          
          }else{
            this.presentAlert();
          }
        });
      }

Everything is working, except for the fact that I can’t use router inside the promise.

It says

uncaught (in promise) TypeError: Cannot read property ‘router’ of undefined

So is there any way of doing that?

Not an expert in vue, but I think you may want to use a fat arrow here

(this: any, r: any)=>{

And basically stop using keyword function as much as possible - I 'd think

1 Like

Yeah i,t worked. Thank you. Sometimes I get confused with regular functions and arrow functions when it comes to using this. It works for arrow fucntions but nor for regular functions or something like that. Anyway it’s solved!

never use the keyword function anymore

1 Like

you might want to taks a look at async/await also - Async/Await and Promises Explained

const r = await articlePublish.sendInfo("savearticle",  info);
if(r.data=="ok"){        
  this.router.replace("/Blog");          
} else {
  this.presentAlert();
}
1 Like