试图等待async执行的setTimeout问题

setTimeout issue trying to wait for execution of async

本文关键字:setTimeout 问题 执行 async 等待      更新时间:2023-09-26

我对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) {
  });