本文介绍了用角度服务链接http.get promises的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是做这件事的不好方法吗?我基本上是在链接诺言,即每次从服务器成功返回时,都会启动一个新的http.get()以获得更多信息,但出错时不要这样做.如果它会导致errorCallback,就不再需要http.get()了!

Is this a bad way to do this? I'm basically chaining promises, where each successful return from server, launches a new http.get() for more information BUT NOT when it errors. No more http.get()s if it causes an errorCallback!

$http.get(...).then(function() {
  $http.get(...).then(function(){
      $http.get(...).then(function(){}, function(){}),
   function(){}); },
mainErrorCallback);

如果不是"$ http.get()",它将在

Would it make a difference if it was instead of "$http.get()" it does "ViewsService.loadViews()" inside the

$http.get(...).then( function() { ViewsService.loadViews(); }, function(){ console.log("error"); }).

这是我的意思,同步地..似乎可行,但是代码需要清理/效率才能看起来更整洁:

http://jsfiddle.net/4n9fao9q/6/

(带有延迟的http请求): http://jsfiddle.net/4n9fao9q/26

(with delayed http requests): http://jsfiddle.net/4n9fao9q/26

推荐答案

$http.get(...).then((res) => {
  //res has data from first http
  return $http.get(...);
}).then((res) => {
  //res has data from second http
  return $http.get(...);
}).then((res) => {
  //res has data from third http
}).catch((err) => {
  //exploded
});

我认为更干净.您可以将$ http.get替换为任何返回promise的函数.如果ViewsService.loadViews()返回一个Promise,则可以使用它.

I think is cleaner. You can replace $http.get with whatever function returns a promise. If ViewsService.loadViews() returns a promise, you can use it.

按照评论中的要求.

...
ViewsService.loadViews = function() {
  //returns a promise
  return $http.get(...);
}

OR

ViewsService.loadViews = function() {
  return new Promise((resolve, reject) => {
    $http.get(...).then((result) => {
      //whatever
      return resolve();
    })
  })
  return $http.get(...);
}

使用loadViews的任何此选项,您可以执行ViewsService.loadViers.then(etc)

With any of this options for loadViews you can do ViewsService.loadViers.then(etc)

这篇关于用角度服务链接http.get promises的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:07