1

I am just starting to learn Angularjs so i might be using the whole thing wrong but please correct me.

I have the following factory that goes like this:

app.factory('MenuService',['service1','service2','service3',function(service1,service2,service3){

    var var1 = [],
        var2 = [],
        var3 = [];

    service1.getDataMethod(function(data){
        // processes data and saves it in var1
    });

    service2.getDataMethod2(function(data)){

    });

    /// same goes for service3.

    return {"prop2": var1, "prop2" : var2, "prop3": var3};
}])

I need to process the data return by service2 , based on data returned in the first service but every time i try to access it, the variable is empty.

I know the functions return a promise, is there a way to tell the second function to wait for the first one to finish in order to be able to use the data it brings?

I hope i made myself understood. Let me know if i should add something else.

1

3 Answers 3

2

Like this?

service1.getDataMethod(function(data){
     // processes data and saves it in var1
}).then(function(data) {
  return service2.getDataMethod2(data)
})

Basically each promise have .then() method. So you can chain this as much as you need a.then().then().then()

In addition, some promise implementations have method wrappers such as .success() and .error(). These methods works similar to .then()

Sign up to request clarification or add additional context in comments.

3 Comments

Hey! Thanks for your response. I tried it with .then(...) but i get the following console error: "service1.getDataMethod(...).then" is not a function
@IvanSt In this case make sure that getDataMethod() return promise
getDataMethod(function(data){....}) the data parameter contains the data returned by getDataMethod and its a resolved promise containing the data. After being processed it gets saved in var1, but when i try to access it from service2.getDataMethod2 to process it, the variable is empty.
0

in angular you have access to $q service that is implementation of q library that works with promises. https://docs.angularjs.org/api/ng/service/$q If you don't like it for some reason try async

Comments

0

Basically you have to chain your promises:

service1.getDataMethod(function(data){
    return something; // this is important, only that way you will be
                      // able to use the next .then()
})
.then(function(something) { // what you returned previously will be the function's argument

    return service2.getDataMethod2(data);
})
.then(function(result) { // `result` is what getDataMethod2 resolves

})
.catch(function(err) {
    // very important to add .catch to handle errors
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.