Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call a method in the Promise in Vue component [duplicate]

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?

like image 843
Jarvis Avatar asked Jun 01 '26 20:06

Jarvis


2 Answers

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.');
    }
}
like image 143
Piotr Szlagura Avatar answered Jun 03 '26 08:06

Piotr Szlagura


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))
like image 29
Lennholm Avatar answered Jun 03 '26 09:06

Lennholm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!