gpt4 book ai didi

javascript - Angular - For 循环 HTTP 回调/ promise

转载 作者:可可西里 更新时间:2023-11-01 17:07:35 26 4
gpt4 key购买 nike

我正在尝试编写一个循环来执行多个 http 请求并将每个响应添加到列表中。

但是,我认为我的做法并不正确。

我认为我没有正确地履行要求的 promise 。 for 循环后的控制台日志显示 myList 数组为空。

代码:

var _myList = []

function getStuff() {

var deferred = $q.defer()

var url = someUrl

$http.get(url).success(function(response) {

if ( response.array.length > 0 ) {

// loop starts here
for ( var i=0; i < response.array.length; i++ ) {

getThing(response.array[i].id);

};
// check the varibale here

console.log(_myList);

deferred.resolve('Finished');

} else {

deferred.resolve('No stuff exists');

};

}).error(function(error) {

deferred.reject(error);

});

return deferred.promise;

};

function getThing(thindId) {

var deferred = $q.defer()

var url = someUrl + thingId;

$http.get(url).success(function(response) {

_myList.push(response);

deferred.resolve(response);

}).error(function(error) {

deferred.reject(error);

});

return deferred.promise;

};

最佳答案

您可以按如下方式简化代码:

var allThings = response.array.map(function(id){
var singleThingPromise = getThing(id);
//return a single request promise
return singleThingPromise.then(function(){
//a getThing just ended inspect list
console.log(_myList);
})
});
$q.all(allThings).then(function(){
//only resolve when all things where resolved
deferred.resolve('Finished');
}, function(e){
deferred.reject('Something went wrong ' + e);
});

关于javascript - Angular - For 循环 HTTP 回调/ promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34662067/

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