Julien Malige Julien Malige - 4 months ago 16
Javascript Question

Order promises execution in AngularJs

I'm working on Angular full-stack with ES6 and babel.

In my controller, I have:

$onInit() {
this.$http.get('/api/example')
.then(() => {console.log("task1")})
.then(() => {console.log("task2")})
}


The console result is what I want:

task1
task2


But when I try to refactor my code:

$onInit() {
this.$http.get('/api/example')
.then(() => {console.log("task1")})
.then(aFunction())
}

aFunction() {
console.log("task2")
}


The console result is:

task2
task1


Why this happens ?

Nb:
.then(() => {this.aFunction()});
seems to work but not seems to be a clean solution.

Answer

You should be passing function reference like .then(aFunction) instead of function call. Currently you are doing aFunction() is immediately invoking that function.

$onInit() { 
    this.$http.get('/api/example')
        .then(() => {console.log("task1")})
        .then(aFunction)
}