【问题标题】:setTimeout issue trying to wait for execution of async尝试等待异步执行的 setTimeout 问题
【发布时间】: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.getsetTimeout 的回调,从而导致无限循环。 屏蔽不好
  • 另一种方法是检查时间差而不是使用 setTimeout,但在 while 循环退出之前,您仍然无法检测到 http 请求何时完成。
  • 谢谢凯文。同意blocking is bad :),真的,我该如何解决这种问题?
  • 这有点意思,你不需要阻止任何东西。
  • 我的猜测是你错误地使用了这个 http 请求的结果,导致你相信你需要阻塞它。

标签: javascript angularjs promise settimeout


【解决方案1】:

$http.get 返回一个承诺,该承诺将在调用完成时解决。 Promise 是一种让 asyncronous 比普通的旧回调更干净、更直截了当的方法。

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

【讨论】:

  • 如果你阅读我的代码,你会发现我已经知道了 Promise 的用法!
  • @maureddu68 但你没有有效地使用它们!
  • 好的,你是对的,直到代码不执行。但我知道我可以在客户端使用 Promise。
  • 一条评论:使用angularJS版本的超时:$timeout。你需要依赖注入它。
  • 糟糕,我打算将其作为有问题的评论发布。
猜你喜欢
  • 2019-10-20
  • 2020-08-06
  • 2021-10-11
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多