循环内的顺序http请求

问题描述 投票:0回答:3

在我的AngularJS应用程序中,我可以有不同数量的http请求来顺序执行。我认为为此需要一个循环:

for (let i = 0; i < $scope.entities.length; i++) {
    MyService.createFixedValue($scope.id, $scope.entities[i]);
}

其中MyService.createFixedValue是http POST请求:

service.createFixedValue = function(property_id, fixed_value_entity){
    return $http({
        method: 'POST',
        url: '/my_url'
        headers: {
            'Content-Type': 'application/json'
        },
        data: fixed_value_entity
    });
}

但是在这种情况下,我的请求是异步的。我需要做些什么更改才能获得顺序请求?

javascript angularjs
3个回答
3
投票

顺序请求(不推荐)

使用for...of至和for...of创建HTTPRequest的顺序循环。

类似于下面的示例构建async / await函数。

async

并通过注入await属性来调用它。

async

单个请求并发送数组(推荐)

仅在单个HTTPRequest中发送整个数组,而不是对每个entity发送请求会更容易。结果将是相同的,但单个请求将更有效。

async function createFixedValues(id, entities) {
  for (const entity of entities) {
    await MyService.createFixedValue(id, entity);
  }
}

将整个$scope数组作为第二个参数。

createFixedValues($scope.id, $scope.entities);

您必须修改请求的服务器端,因为您现在要发送一个数组而不是单个值。但是您尚未指定如何处理服务器端响应,因此由您自己决定。


1
投票

要顺序发出HTTP请求,请使用service.createFixedValue = function(property_id, fixed_value_entities) { return $http({ method: 'POST', url: '/my_url' headers: { 'Content-Type': 'application/json' }, data: fixed_value_entities }); } $scope.entities

MyService.createFixedValue($scope.id, $scope.entities);

有关更多信息,请参阅

  • $q.all
  • array.reduce

0
投票

[也许尝试不返回http POST请求。实际上,您可能不需要在函数中返回任何内容。只需执行发布请求即可。如果需要捕获响应,则将其推送到全局数组中。

© www.soinside.com 2019 - 2024. All rights reserved.