gpt4 book ai didi

javascript - 在我的案例中如何发出多个 http 请求

转载 作者:行者123 更新时间:2023-11-29 10:39:39 25 4
gpt4 key购买 nike

我正在尝试使用 Angular $resource 链接一个 promise。

我有以下工厂:

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

我使用我的产品工厂进行多个查询:

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
})
})
})

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

最佳答案

您可以将 promise 链接在一起!

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
})

关于javascript - 在我的案例中如何发出多个 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31419003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com