2

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?

Jarvis
  • 371
  • 1
  • 10
  • 22

3 Answers3

7

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.');
    }
}
Piotr Szlagura
  • 650
  • 5
  • 15
1

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))
Lennholm
  • 7,205
  • 1
  • 21
  • 30
1
testMethod() {
    someRequestMethod(someRequestData).then(() => {
        this.outMethod_01()
    }).then(function() {
        this.outMethod_02()
    })
}

this works.

Jarvis
  • 371
  • 1
  • 10
  • 22
  • This is the perfect answer so fur, with vue and axios using the '.then(function(response) => {....' failed for me but changing to '.then((response) => {' as suggested worked like charm – Software Developer Jan 08 '20 at 09:45