如何获得在我的例子多的http请求的结果吗?我的、如何获得、例子、结果

2023-09-13 04:19:58 作者:女人何苦作贱自己

我试图做一个HTTP请求和返回的结果放入我的数组。

I am trying to make a http request and place the returned result into my array.

我有这样的事情

按Ctrl

for (var i=0; i < numOfProduct.length; i++) {
   productFactory.makeRequest(numOfProduct[i].id)
                    .then(function(data) {
                        console.log(i)
                        //always output 10 which is my numOfProduct.length

                        numOfProduct[i].push({detail: data}); 
                        //i got Cannot read property 'push' of undefined error
                    })
                $scope.numOfProduct = numOfProduct;
}

productFactory

productFactory

service.makeRequest = function(id) {
    return $http.get('/api/product/get' + id);
}

return service;

我的目标是一个http请求的结果推到每个numOfProduct元素作为对象。不过,我似乎无法做到这一点与HTTP请求codeS我有。谁能帮我一下吗?非常感谢!

My goal is to push a http request result into each of numOfProduct element as an object. However, I can't seem to do that with the http request codes I have. Can anyone help me about it? Thanks so much!

推荐答案

您有以上两个问题:

1是一个常见的​​问题,回调的地方要绑定一个参考 I 而不是 I 。所以,你的回调函数被调用时,循环将完成和 I 将是10在所有的回调,你绑定。

1 is a common callback issue where you're binding a reference to i but not to the value of i. So, by the time your callback gets called, the loop will have finished and i will be 10 in all of the callbacks that you bound.

解决这个问题的方法之一是强制评估 I 通过函数调用:

One way to fix this is to force evaluation of i through a function call:

function makeCallback(productId) {
 productFactory.makeRequest(productId)
                    .then(function(data) {
                        console.log(i)
                        return ({detail: data}); 
                    });
} 

第二个问题是,您所呼叫 .push 对数组中的一个特定值 numOfProduct 代替实际的数组。 (除非特定的值是一个数组,我假设它是不是因为你是叫 .ID 上的值)

The second issue is that you are calling .push on a specific value in the array numOfProduct instead of an actual array. (Unless that specific value is an array, which i'm assuming it isn't since you are calling .id on the value)

试试这个:

function makeCallback(productId) {
     productFactory.makeRequest(productId)
                        .then(function(data) {
                            console.log(i)
                            return ({detail: data}); 
                        })
}
var array = [];
for (var i=0; i < numOfProduct.length; i++) {    
    array.push(makeCallback(numOfProduct[i].id));
}
$scope.numOfProduct = array;

如果每个循环正在运行异步那么我建议使用流行的异步libary 。让我知道如果您需要任何帮助设置此功能。

If each loop is being ran asynchronously then I suggest using the popular async libary. Let me know if you need any help setting this up.