在我的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
});
}
但是在这种情况下,我的请求是异步的。我需要做些什么更改才能获得顺序请求?
使用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);
您必须修改请求的服务器端,因为您现在要发送一个数组而不是单个值。但是您尚未指定如何处理服务器端响应,因此由您自己决定。
要顺序发出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
[也许尝试不返回http POST请求。实际上,您可能不需要在函数中返回任何内容。只需执行发布请求即可。如果需要捕获响应,则将其推送到全局数组中。