试图等待async执行的setTimeout问题
setTimeout issue trying to wait for execution of async
我对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();
和asynccontentinfo是:
function AsyncContentInfos(URL) {
this.URL = URL;
this.responseData = [];
this.promiseObject;
}
$http.get
返回一个promise,该promise将在调用完成时解析。承诺是一种使异步比普通的回调更干净、更直接的方法。
getAsyncContent: function (asyncContentInfos) {
return $http.get(asyncContentInfos.URL, { cache: true })
.then(function (response) {
return response.data;
}, function (errResponse) {
console.error(err_msg);
throw errResponse;
});
}
然后使用:
getAsyncContent({...}).then(function(yourDataIsHere) {
});
承诺的好处是它们可以很容易地链接起来。
getAsyncContent({...})
.then(function(yourDataIsHere) {
return anotherAsyncCall(yourDataIsHere);
})
.then(function(your2ndDataIsHere) {
});
相关文章:
- 使setInterval和setTimeout工作时出现问题
- setTimeout调用自身的任何问题
- javascript 中的 setTimeout 问题
- 正在清除setTimeout问题
- 奇怪的setTimeout问题
- Javascript setTimeout问题w/ for循环
- 点击()和setTimeout问题
- iOS设备上HTML5 canvas中的Javascript setTimeout问题
- jQuery记忆技巧游戏setTimeout()问题
- 在setTimeout问题中更新JSON对象
- Node.js中的SetTimeout问题
- AngularJS加载图像指令setTimeout问题
- For循环中的setTimeout问题
- 有人可以帮助我一个小的JavaScript setTimeout问题
- 如何解决ie浏览器setTimeout问题?
- setTimeout问题,则没有超时
- 循环和setTimeout问题的Javascript
- FireFox 插件 / javascript setTimeout 问题
- 简单的javascript settimeout问题
- 试图等待async执行的setTimeout问题