【发布时间】:2015-05-21 18:08:38
【问题描述】:
我是 javascript 中此类问题的新手,我无法修复这种尝试,以等待结合 Angular 承诺对象和超时的异步调用。
onTimeout 函数似乎永远不会执行。
getAsyncContent: function (asyncContentInfos) {
var deferObj = $q.defer();
var promiseObj = deferObj.promise;
asyncContentInfos.promiseObject = promiseObj;
var blockingGuard = { done: false };
promiseObj.then(function () {
blockingGuard.done = true;
});
this.wait = function () {
var executing = false;
var onTimeout = function () {
console.log("******************** timeout reached ********************");
executing = false;
};
while (!blockingGuard.done) {
if (!executing && !blockingGuard.done) {
executing = true;
setTimeout(onTimeout, 200);
}
}
};
$http.get(asyncContentInfos.URL, { cache: true })
.then(function (response) {
asyncContentInfos.responseData = response.data;
console.log("(getAsyncContent) asyncContentInfos.responseData (segue object)");
console.log(asyncContentInfos.responseData);
deferObj.resolve('(getAsyncContent) resolve');
blockingGuard.done = true;
return /*deferObj.promise*/ /*response.data*/;
}, function (errResponse) {
var err_msg = '(getAsyncContent) ERROR - ' + errResponse;
deferObj.reject(err_msg);
console.error(err_msg);
});
return {
wait: this.wait
}
}
客户端代码是这样的:
var asyncVocabulary = new AsyncContentInfos(BASE_URL + 'taxonomy_vocabulary.json');
getAsyncContent(asyncVocabulary).wait();
而 AsyncContentInfos 是:
function AsyncContentInfos(URL) {
this.URL = URL;
this.responseData = [];
this.promiseObject;
}
【问题讨论】:
-
while 循环运行时,无法执行对
$http.get和setTimeout的回调,从而导致无限循环。 屏蔽不好。 -
另一种方法是检查时间差而不是使用 setTimeout,但在 while 循环退出之前,您仍然无法检测到 http 请求何时完成。
-
谢谢凯文。同意blocking is bad :),真的,我该如何解决这种问题?
-
这有点意思,你不需要阻止任何东西。
-
我的猜测是你错误地使用了这个 http 请求的结果,导致你相信你需要阻塞它。
标签: javascript angularjs promise settimeout