尝试等待执行异步的setTimeout问题

时间:2015-05-21 18:08:39

标签: javascript angularjs promise settimeout

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

1 个答案:

答案 0 :(得分:2)

$http.get返回一个将在呼叫完成时解析的承诺。承诺是一种使异步更干净,更直接的方式,而不是简单的旧回调。

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