ajax – AngularJS – 对$q.all()的失败恢复

前端之家收集整理的这篇文章主要介绍了ajax – AngularJS – 对$q.all()的失败恢复前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试填补一些解决一系列远程调用的本地数据。
当每个承诺得到解决时,我加载数据并继续。

方法$ q.all([])正是这样做的:

  1. $q.all([
  2. this.getUserInfo(11)
  3. .then(function (r) {
  4. results.push(r)
  5. }),this.getUserConns()
  6. .then(function (r) {
  7. results.push(r)
  8. }),this.getUserCtxs()
  9. .then(function (r) {
  10. results.push(r)
  11. })
  12. ])
  13. .then(function () {
  14. console.log(results)
  15. })

问题是,这段代码没有弹性。
如果这些呼叫中的任何一个失败,没有人得到鱼!

调用包装在try / catch语句中,简单地导致$ q.all()完全忽略该条目,即使没有失败(请注意func中的console.log)…

  1. $q.all([
  2. this.getUserInfo2(11)
  3. .then(function (r) {
  4. results.push(r)
  5. }),function () {
  6. try {
  7. this.getUserGroups()
  8. .then(function (r) {
  9. console.log(r)
  10. results.push(r)
  11. })
  12. }
  13. catch (err) {
  14. console.log(err)
  15. }
  16. },])
  17. .then(function () {
  18. console.log(results)
  19. })

输出

[Object]

任何提示我如何包装它是有弹性的?

感谢@dtabuenc,我已经走了一步。
实现错误回调,我可以避免破坏链,并推动已解决的承诺的值。

但是,令人讨厌的异常仍然显示在控制台上
如果我无法尝试/捕获异步请求,我该如何解决

来电显示

  1. return $q.all([
  2.  
  3. this.getUserInfo(user_id)
  4. .then(function (r) {
  5. results['personal_details'] = r
  6. }),this.getUserConns()
  7. .then(
  8. function (r) {
  9. results['connections'] = r
  10. },function(err) {
  11. console.log(err)
  12. })
  13.  
  14. ])
  15. .then(function () {
  16. return (results)
  17. })

代码(注入异常)

  1. getUserConns: function() {
  2.  
  3. return __doCall( ws.getUserConnections,{} )
  4. .then( function(r) {
  5.  
  6. // very generic exception injected
  7. throw new Error
  8.  
  9. if (r && r.data['return_code'] === 0) {
  10. return r.data['entries']
  11. }
  12. else {
  13. console.log('unable to retrieve the activity - err: '+r.data['return_code'])
  14. return null
  15. }
  16. })
  17. },
这将工作,但也将错误推送到阵列。
  1. function push(r) {
  2. results.push(r);
  3. }
  4.  
  5. $q.all([
  6. this.getUserInfo(11).then(push).catch(push),this.getUserConns().then(push).catch(push),this.getUserCtxs().then(push).catch(push)
  7. ])
  8. .then(function () {
  9. console.log(results);
  10. })

你也应该提高你对承诺的理解,你永远不应该使用try-catch的承诺 – 当使用promises,你使用.catch()方法(其他一切都是隐含的尝试)。这适用于正常错误以及异步错误

如果你想完全忽略错误

  1. function push(r) {
  2. results.push(r);
  3. }
  4.  
  5. function noop() {}
  6.  
  7. $q.all([
  8. this.getUserInfo(11).then(push).catch(noop),this.getUserConns().then(push).catch(noop),this.getUserCtxs().then(push).catch(noop)
  9. ])
  10. .then(function () {
  11. console.log(results);
  12. })

猜你在找的Ajax相关文章