Angular promise between two functions

时间:2016-05-05 08:45:11

标签: javascript angularjs angular-promise

I've got two functions

var firstFunction = function(aPromise) {
    //Do stuff

    return aPromise.resolve();
}


var secondFunction = function(i) {

    var defer = $q.defer;

    //Do stuff with i (an index) - used for anadromic calls.

    firstFunction(defer).promise.then(function() {

        i++;
        secondFunction(i);

    })

}

I need the second function to wait the promise from the first function to call itslef. Is this syntax correct ?

After request I add the purpose of my code.

I've got:

Categories > Products > Favourites which I have to call from server.

For each category I have to get the products and for each product I have to check if it is favourite. The bad thing is that in current situation I've got to make many calls which are all asynchronous and one have to wait the other.

2 个答案:

答案 0 :(得分:0)

我正在使用下面的代码,这对我有用。我在一个不同的方法中调用此代码,这是等待我从服务器获取响应

var promise = [XYZService.locations($scope.newrecord.state.Text)]
$q.all(promise).then(function (data) {
$scope.addnewrecord.locations = data[0];
});

这里,根据状态,我从服务器获取各自的位置,并将位置绑定到模型

答案 1 :(得分:0)

我认为不应该像firstFunction()中的参数一样发送延迟,而var defer = $q.defer;必须是var defer = $q.defer();

如果想要从服务中获取数据,您可以在AngularJS中使用resolve,请阅读解释性文章:http://www.undefinednull.com/2014/02/17/resolve-in-angularjs-routes-explained-as-story/。我希望它可以帮到你。