简体   繁体   中英

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.

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)
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM