setTimeout issue trying to wait for execution of async

若如初见. 提交于 2020-01-17 01:17:24

问题


I'm new to this kind of problem in javascript and i can't fix this attempt to wait for an asynchronous call combining Angular promise objects and timeouts.

The function onTimeout seems never execute.

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
    }
}

Client code is something like this:

var asyncVocabulary = new AsyncContentInfos(BASE_URL + 'taxonomy_vocabulary.json');
getAsyncContent(asyncVocabulary).wait();

And AsyncContentInfos is:

function AsyncContentInfos(URL) {
    this.URL = URL;
    this.responseData = [];
    this.promiseObject;
    }

回答1:


$http.get returns a promise which will resolve when the call completes. Promises are a way to make asyncronous more clean and straight lined than plain old callbacks.

getAsyncContent: function (asyncContentInfos) {

    return $http.get(asyncContentInfos.URL, { cache: true })
        .then(function (response) {
            return response.data;
        }, function (errResponse) {
            console.error(err_msg);
            throw errResponse;
        });
}

Then using it:

getAsyncContent({...}).then(function(yourDataIsHere) {

});

The nice thing about promises is that they can be easily chained.

getAsyncContent({...})
  .then(function(yourDataIsHere) {
     return anotherAsyncCall(yourDataIsHere);
  })
  .then(function(your2ndDataIsHere) {
  });


来源:https://stackoverflow.com/questions/30381270/settimeout-issue-trying-to-wait-for-execution-of-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!