如何角承诺。后来作品 [英] How angular promise .then works

查看:154
本文介绍了如何角承诺。后来作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来AngularJS $ q和承诺,我知道如果我使用 $ http.get(),我可以得到一个承诺,我可以使用它的。然后功能chainly像

  $ http.get(URL)
     。然后(功能(数据){}功能(错误){})
     。然后(功能(数据){}功能(错误){})
     .....

每个然后返回一个新的承诺,但我的问题是我怎么知道那件事已经解决?有一件事我注意到的是如果我添加返回功能(数据){} ,接下来则功能可以从previous然后函数的返回值,这样做这意味着我需要给予回报的决心?


解决方案

  

我怎么知道那件事已经解决?


当你注意到的,由返回的承诺,则()是指在执行回调后得到解决(第一承诺得到满足时执行)。而且它与来自确实回调的结果解决。


  

我需要给一个回报的决心?


没有,如果你从回调不收益什么,结果是未定义 - 就像用普通函数调用。

不过,你实际上有更多的选择建立在你的回调比返回普通值的结果:


  • 您可以收益另一个承诺。通过返回的承诺,则()将采取它,即其结果符合或很快其原因拒绝,因为它落户。

  • 您可以罚球例外。它会得到自动捕获并由此产生的承诺将被拒绝,该错误。

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

$http.get(url)
     .then(function(data){}, function(err){})
     .then(function(data){}, function(err){})
     .....

Each then return a new promise, but my question is how do I know that then has been resolved? One thing I notice is if I add return to the function(data){}, the next then function can get that return value from previous then function, so does that mean I need give a return as resolve?

解决方案

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.

这篇关于如何角承诺。后来作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆