简体   繁体   English

一次多次拨打同一服务

[英]Call same service multiple times at the same time

I have an $http service (or factory). 我有一个$http服务(或工厂)。

angular.module("app")
    .factory("PriceService", function ($http) {
        return {
            get: function (item) {
                var url = "/pricing";

                return $http.post(url, item);
            }
        }
    }); 

I am reading items from an Excel file. 我正在从Excel文件中读取项目。 And each item will call the service once. 每个项目将调用一次服务。

for (item in excelItems) {
    console.time(item.referenceId);
    PriceService.get(item).then(function(response) {
        console.timeEnd(item.referenceId);
        // process result
    }, function() {
        // error
    })
}

The for loop finishes instantly, so all items should call PriceService almost at the same time. for循环立即完成,因此所有项目都应几乎同时调用PriceService However, it seems that the items are calling the service one after another. 但是,似乎这些项目正在一个接一个地调用服务。 Please see the console time results (the left column is refereceId). 请查看控制台时间结果(左列为RefereceId)。

    3: 2283.264ms
    5: 3167.943ms
    2: 3327.372ms
    11: 3767.073ms
    12: 3849.267ms
    14: 5388.853ms
    8: 15996.263ms
    16: 16636.952ms
    4: 17689.306ms
    18: 18190.733ms
    15: 19323.512ms
    20: 20009.020ms
    13: 23326.644ms
    10: 23378.259ms
    22: 24077.294ms
    24: 24568.147ms
    total: 24570.348ms

Is there any way that I can improve this? 有什么办法可以改善这个状况? Thanks a lot! 非常感谢!

You can use a different approach. 您可以使用其他方法。 If every request is idempotent you can use the $q module by this way: 如果每个请求都是幂等的,则可以通过以下方式使用$ q模块:

var promises = [];
for (item in excelItems) {
    promises.push(PriceService.get(item));
}
$q.all(promises).then(function(results){
    //Ok
}, function(error){
    console.log(error);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM