gpt4 book ai didi

javascript - 等待异步调用在其他地方启动时返回

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

我试图找到这个问题的答案,并开始阅读有关 promise /延期的内容,但是当从其他地方开始时,我不知道如何解决这个问题。

    angular.module('myapp.utilities').factory('codetabelService', ['Restangular', function(Restangular) {
var initialized = false;
var listtopopulate1 = [];
var listtopopulate2 = [];

var update = function() {
Restangular.all('codeTabel').getList()
.then(function(codetabellen) {
codetabellen.forEach(function(entry) {
//do some processing on return values
listtopopulate1.push(entry);
listtopopulate2.push(entry);
});
initialized=true;
});
};

return {
initialize: function() {
if (!initialized) {
update();
}
},
getListValuesType1: function() {
//How do I wait here for initialized to become true?
return listtopopulate1;
},
getListValuesType2: function() {
//How do I wait here for initialized to become true?
return listtopopulate2;
}
};
}]);

所以我想做的是在我的单页应用程序启动时缓存一些值。在我的根 Controller 上,我调用初始化方法,该方法启动对后端的异步调用。当加载我的 View 并且 Controller 将范围值设置为 getListValuesType1() 的结果时,异步调用有时尚未完成。

因为异步加载不是由调用方法 getListValuesType1() 的 Controller 触发的,所以我不确定 Promise 是否会在这里工作(我承认,我对此还是新手)

我发现you can put a timer on it ,但这似乎不对。只是感觉有更好的解决方案。

最佳答案

是的,您可以有效地使用 Promise 和 Promise 缓存来执行此操作,实现此目的的一种方法是:-

angular.module('myapp.utilities').factory('codetabelService', ['Restangular', '$q', function(Restangular, $q) {

var initialized;//Use this to cache the promise
var listtopopulate1 = [];
var listtopopulate2 = [];

var _initialize = function() {
//If already initialized just return it which is nothing but the promise. This will make sure initialization call is not made
return initialized || (initialized= Restangular.all('codeTabel').getList()
.then(function(codetabellen) {
codetabellen.forEach(function(entry) {
listtopopulate1.push(entry);
listtopopulate2.push(entry);
});
//Note- You could even return the data here
}, function(){
//Just clean up incase call is a failure.
initialized = null;
//Just reject with something if you want to:-
//return $q.reject("SomeError")
}));
};

return {
initialize: function() {
return _initialize(); //Just return promise incase you want to do somthing after initialization
},
getListValuesType1: function() {
return _initialize().then(function(){ //return promise with a chain that resolves to the list
return listtopopulate1;
});
},
getListValuesType2: function() {
return _initialize().then(function(){ //return promise with a chain that resolves to the list
return listtopopulate2;
});
}
};
}]);

在使用它时,您可以执行以下操作:-

codetabelService.getListValuesType1().then(function(list){
$scope.list1 = list;
});

有了这个,您甚至可以摆脱合约中的 initialize 调用,并仅在第一次使用 getListX 方法期间进行 ajax 调用。

关于javascript - 等待异步调用在其他地方启动时返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27451583/

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