javascript - AngularJS $q.all - 在 http 调用之间等待

标签 javascript angularjs http settimeout

因此,我遇到的情况是,我需要执行一堆 http 调用,然后一旦完成,就继续执行该过程的下一步。

下面是执行此操作并且工作正常的代码。

但是,我现在需要在每个 http 调用之间等待几秒钟。有没有办法在我当前的设置中传递超时,或者是否会涉及大量重构?

如果需要,可以发布更多代码。我尝试将超时配置变量传递到 http 调用中,但是,它们仍然同时被触发。

任何建议都会很棒。

代码

 var allThings = array.map(function(object) {
     var singleThingPromise = getFile(object.id);
     return singleThingPromise;
 });
 $q.all(allThings).then(function() {
     deferred.resolve('Finished');
 }, function(error) {
     deferred.reject(error);
 });

最佳答案

您可能希望在前一个成功后执行顺序调用,而不是使用 $q.all,并且可能使用 $timeout。也许你可以构建一个递归函数。

类似这样的事情..

function performSequentialCalls (index) {
  if(angular.isUndefined(array[index])) {
    return;
  }
  getFile(array[index].id).then(function() {
    $timeout(function() {
      performSequentialCalls(index + 1)
    }, 1000) // waiting 1 sec after each call
  })
}

正确注入(inject)所需的东西。这假设 array 包含具有 id 的对象,您可以使用这些对象执行 API 调用。还假设您正在使用 $http。如果使用 $resource,请相应地添加 $promise

希望对您有所帮助!

关于javascript - AngularJS $q.all - 在 http 调用之间等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45564686/

相关文章:

http - POST 数据是否应该在超时条件下重试?

php - 如何修复网络解决方案 ssl 代理的错误

javascript - 在 Express.js 中使用 PUT 方法

angularjs - $route.current 在尝试获取当前参数时未定义

AngularJS $http.get 返回速度不够快

javascript - 如果多个复选框选中,如何发出警报 C#

Java jackson : deserialize complex polymorphic object model: JsonMappingException: Unexpected token (START_OBJECT), 应为 VALUE_STRING

javascript - 当 AngularJS 缓存 HTTP 请求时,它缓存解析的 JSON 对象还是字符串响应本身

javascript - 未捕获的语法错误 : Unexpected end of input Google Charts

javascript - 如何在 firebase 中向用户添加自定义配置文件详细信息?