我对 JavaScript 中的此类问题很陌生,我无法修复此等待结合 Angular Promise 对象和超时的异步调用的尝试。
函数 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;
}
最佳答案
$http.get
返回一个 promise ,该 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) {
});
Promise 的好处是它们可以轻松链接。
getAsyncContent({...})
.then(function(yourDataIsHere) {
return anotherAsyncCall(yourDataIsHere);
})
.then(function(your2ndDataIsHere) {
});
关于javascript - setTimeout 尝试等待异步执行的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30381270/