如何使多个http请求在我的情况下

How to make multiple http requests in my case

本文关键字:我的 情况下 请求 http 何使多      更新时间:2023-09-26

我正在尝试用Angular $resource链接一个承诺。

我有以下工厂:

angular.module('myApp').factory('Product', ['$resource', function ($resource) {
    return $resource(
        '/api/product/:name',
        { name: '@name' },
        { 'getSub': {
                url: '/api/product/getSub/:name',
                method: 'GET'}
         }
    );
}]);

我使用我的Product factory进行多个查询:

Product.query({'name': name}, function(product) {
     Product.getSub({'name': product.name}, function(subItem) {
         Product.getSub({'name':subItem.name}, function(childItem) {
             //do stuff with child item
         })
     })
})

有更好的方法吗?我觉得嵌套所有这些调用不是最佳实践。

您可以将承诺链接在一起!

Product.query({'name': name}).$promise
.then(function(product){
  return Product.getSub({'name': product.name}).$promise;
})
.then(function(subItem){
  return Product.getSub({'name': subItem.name}).$promise;
})
.then(function(item){
  // etc
})

你可以使用瀑布的异步库或实现自己。
以下是您的示例代码。

async.waterfall([
    function(callback) {
        Product.query({'name': name}, function(product) {
            callback(null, product);
        })
    },
    function(product, callback) {
        Product.getSub({'name': product.name}, function(subItem) {
            callback(null, product, subItem);
        })
    },
    function(product, subItem, callback) {
        Product.getSub({'name':subItem.name}, function(childItem) {
            var result = {};
            result.childItem = childItem;
            result.subItem = subItem;
            result.product = product;
            callback(null, result);
        })
    }
], function (err, result) {
    //do stuff with result
});

如果您希望请求一个接一个地完成(就像您在示例中那样),您可以执行这样的递归函数:

在这个例子中,我想上传一对图片(调用HTTP路由):

$scope.uploadImageLayout = function (currentIndex, numberOfItems) {
        if (currentIndex === numberOfItems) {
            // in here you could do some last code after everything is done
        } else {
            Upload.upload({
                url: 'localhost:3000/ficheiros',
                file: $scope.imagesToUpload[$scope.auxIndex].file
            }).success(function (data, status, headers, config) {
                if ($scope.auxIndex < numberOfItems) {
                    $scope.uploadImageLayout(currentIndex + 1, numberOfItems);
                }
            });
        }
    };

第一次调用时这样做:

$scope.uploadImageLayout(0, $scope.imagesToUpload.length);

在你的情况下是一样的,但不是Upload。上传请求,你应该有你的请求,并捕获回调函数。

一个有用的解决方案可能是使用$q库

https://docs.angularjs.org/api/ng/service/美元q

你可以使用$q.all()方法来发送大量的请求并且只管理一个回调然后()或者使用$q.defer()并解决拒绝你自己的承诺。

我目前从移动设备回答这个问题,我不能举个例子。很抱歉。如果当我回到家,火车仍然试图帮助我