Reputation: 3475
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.
Upvotes: 2
Views: 57
Reputation: 136144
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)
}
Upvotes: 6
Reputation: 4766
aFunction
is executed immediately and its result passed into the .then()
.
It should be : .then(aFunction)
This will pass a reference to the .then
which it will execute itself.
Upvotes: 4