使用AngularJS 1.0.7中的$ http嵌套承诺

时间:2017-09-26 07:12:18

标签: javascript angularjs

我试图了解Promular如何在Angular 1.0.7中运行,但语法和概念对我来说很难。我创建了一个相关的上一篇文章Nesting promises with $resources in AngularJS 1.0.7,它正常运行。但是,当我尝试使用$resource服务取代$http时,我不会按预期为我工作。

代码永远不会等待承诺的到来,我得不到任何结果。

我附上了代码:

// URL has to be parsed to get the destination, language and boatType       
var parseURL = function() {
    var language = $routeParams.language;
    var url = $location.path();

    var deferred = $q.defer();
    var promise = deferred.promise;
    promise.then(function success(result) {
        var destination = result;
        console.log("destination:" + destination);
        searchBoats(destination);
    });

    parseDestination(url, language).then(deferred.resolve);
};
parseURL();

var parseDestination = function(url, language) {
    console.log("parseDestination.begin");
    var departure = UrlService.parseUrlDeparture(url);

    var deferred = $q.defer(),
        promise = deferred.promise;
    TranslationService.getTranslatedDeparture(departure, language, API_SERVER_URL, deferred.resolve, deferred.reject);
    return promise;
};


// The function in the service
getTranslatedDeparture: function(destination, language, api) {
    var defered = $q.defer();
    var destinationPromise = defered.promise;
    $http.get("http://" + api + "/translatedDepartures?departure=" + destination + ";lang=" + language + ";matchStart=" + true).then(
        //var destination = result.data.map(function (source) { return source.element_translation; });
        defered.resolve
    );
    return destinationPromise;
}

1 个答案:

答案 0 :(得分:2)

你正在以可想象的每一种方式使用承诺错误。承诺旨在被链接并使用.then()创建新的承诺。这样做可以解决您的错误并将代码长度缩短一半。只要您承诺开始(由于$http.get返回承诺而执行),您不需要也不应该使用$q.defer()

// URL has to be parsed to get the destination, language and boatType       
var parseURL = function() {
    var language = $routeParams.language;
    var url = $location.path();

    parseDestination(url, language)
        .then(function (result) {
            var destination = result;
            console.log("destination:", destination);
            searchBoats(destination);
        });    
};
parseURL();

var parseDestination = function(url, language) {
    console.log("parseDestination.begin");
    var departure = UrlService.parseUrlDeparture(url);

    return TranslationService.getTranslatedDeparture(departure, language, API_SERVER_URL);    
};


// The function in the service
getTranslatedDeparture: function(destination, language, api) {
    var url = "http://" + api + "/translatedDepartures?departure=" + destination + ";lang=" + language + ";matchStart=" + true;

    return $http.get(url)
        .then(function (result) { return result.data; });  
}