In a Vue component:
import { someRequestMethod } from '@/api/requ'
...
methods: {
testMethod() {
someRequestMethod(someRequestData).then(function() {
this.outMethod_01()
}).then(function() {
this.outMethod_02()
})
}
outMethod_01() {
console.log('I am an outer method 01.');
}
outMethod_02() {
console.log('I am an outer method 02.');
}
}
when I call testMethod, with a Promise response.
then I want to call outMethod_01 if succeed, outMethod_02 if got error.
but i got error outMethod_01 is undefined and outMethod_02 is undefined.
so how to call a outer method in the Promise?
You should use arrow function syntax (params) => {...code} instead of function(params) {...code}. In arrow function this is inherited from the scope. In regular function, this is the function itself (it has its own scope).
You can learn more here: https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4
If you can't use ES6 syntax, you could do something like:
methods: {
testMethod() {
var self = this;
someRequestMethod(someRequestData).then(function() {
self.outMethod_01()
}).then(function() {
self.outMethod_02()
})
}
outMethod_01() {
console.log('I am an outer method 01.');
}
outMethod_02() {
console.log('I am an outer method 02.');
}
}
Instead of wrapping the calls in anonymous functions you can hit two birds with one stone by using bind():
someRequestMethod(someRequestData)
.then(this.outMethod_01.bind(this))
.then(this.outMethod_02.bind(this))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With