简体   繁体   中英

Call same service multiple times at the same time

I have an $http service (or factory).

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. 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. However, it seems that the items are calling the service one after another. Please see the console time results (the left column is 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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