gpt4 book ai didi

javascript - $http promise 不等待完成它内部的循环

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

我试图在 $http 请求中运行 AngularJS forEach 循环,其中 promise 不等待完成循环并在此之前返回。

请在下面找到我的代码:

return $http({
method: 'GET',
url: $rootScope.baseUrl + 'test/test/test/test',
headers: {
"token": token
}
})
.then(function(responce) {
var dashboardCheck = function() {
var defer = $q.defer();
angular.forEach($rootScope.getDashboardDetails.dashboardList, function(value, key) {
if (value.name == "Dashboard" && value.contentDashboard == true) {
//return value;
defer.resolve(value);
}
})
return defer.promise;
}
var availableDashboard = function() {
return $rootScope.getDashboardDetails.dashboardList[0];
}
var defaultDash = function(value) {
method goes here
}
if (dashboardCheck()) {
defaultDash(dashboardCheck());
} else {
defaultDash(availableDashboard())
}
})

最佳答案

你似乎让一切都变得比它应该的更复杂,你想要找到某个仪表板,如果找不到就返回第一个。

发出请求后没有异步代码,您也没有对请求执行任何操作,所以我不确定您一开始为什么要这样做。

你想要做的事情的更简单的版本是这样的:

return $http({
method: 'GET',
url: $rootScope.baseUrl + 'test/test/test/test',
headers: {
"token": token
}
})
.then(function(responce) {
var scopeDashboard = $rootScope.getDashboardDetails.dashboardList;
var dashboard =
//not sure why need to return a defer here, no async code provided
scopeDashboard.filter(
dashboard=>
dashboard.name == "Dashboard" && dashboard.contentDashboard == true
)[0] || scopeDashboard[0];
// if scopeDashboard is an object try this
// scopeDashboard[
// Object.keys(scopeDashboard)
// .filter(
// key=>
// scopeDashboard[key].name == "Dashboard" &&
// scopeDashboard[key].contentDashboard == true
// )[0] || 0
// ];
return [dashboard,response];
})
.then(
([dashboard,response])=>{
//you now have the response and dashboard, what would you like to do with it?
}
)
.catch(
err=>console.error("something went wrong",err)
)

关于javascript - $http promise 不等待完成它内部的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47797874/

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