How angular promise .then works

后端 未结 2 888
清歌不尽
清歌不尽 2021-01-15 09:56

I am new to AngularJS $q and promise, I learn that if I use $http.get(), I can get a promise and I can use its .then function chainly like

相关标签:
2条回答
  • 2021-01-15 10:12

    how do I know that then has been resolved?

    As you noticed, the promise returned by then() is resolved after the callback is executed (which is executed when the first promise is fulfilled). And it does resolve with the result from the callback indeed.

    Do I need give a return as resolve?

    No, if you don't return anything from the callback, the result is undefined - just like with regular function calls.

    However, you do in fact have more options to build a result in your callback than returning a plain value:

    • You can return another promise. The promise returned by then() will adopt it, i.e. fulfills with its result or reject with its reason as soon as it settles.
    • You can throw an exception. It will get automatically caught and the resulting promise is rejected with that error.
    0 讨论(0)
  • 2021-01-15 10:31

    The initial promise has been resolved when the callback of the first then executes, but you can chain thens like you described. Each then invocation creates a new derived promise. If you return a concrete value from a then callback the derived promise will be resolved with that value. You will be able to access that value as an argument in the subsequent then callback

    serviceCall().then(function(){})//nothing returned => resolves with undefined value
                 .then(function(){return 10;})//will resolves with the value 10
                 .then(function(data){//data is 10 here
                  });
    

    Basically there is no need to manually resolve promises. You can also call external functions that return promises like other $http requests as well.

    serviceCall().then(function(){
      return $http.get('/get-customer-from-server');//returns customer
    })
    .then(function(customer){
      //the customer is available here
    })
    

    For brevity I was omitting the error callback. The error callback will execute if any of the promises were rejected, which is likely to be due to a failure somewhere. There is a short hand notation for error handling. Instead of a then with two callbacks you can use catch

    serviceCall().then(function(){
    })
    .catch(function(){//error handling if promise was rejected
    }) 
    

    catch is an alias for .then(null,function(){});

    More info here: http://www.syntaxsuccess.com/viewarticle/angular-promise-chaining-explained

    0 讨论(0)
提交回复
热议问题