Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple `.then()`s on single angularjs promise -- all use _original_ data

I'm writing an angularjs app relying on promises, and though it's working, I wonder if I could do it more optimally.

At the beginning of the code, I'm creating a promise that goes off to fetch some data. When this is done, I want to run several functions that all use this data. The functions are attached at unrelated parts of the app, so I do not know the order in which they're attached to the promise. They do not need to be done in sequence either.

app.service("Fetch", function ($q){
    return function() {
        var def = $q.defer();
        somelibrary.asynccall(function(error, data){ //callback
            if (error) def.reject(error);
            else def.resolve(data);
        });
        return def.promise;
    };
});

app.controller("ctrl", function ($scope, Fetch) {
    var prom = Fetch();

    //somewhere:
    prom.then(function(data){$scope.var1 = data["VAR1"];});
    //somewhere else:
    prom.then(function(data){$scope.var2 = data["VAR2"]});
});

The main disadvantage here is that the later thens are only executed whenever the preceding ones are finished, which is not necessary here.

Also, I need to add return data inside every function(data){...}, otherwise the following then() does not have the data available.

Is there not another way to do this, more apt for this situation?


EDIT: as mentioned by @jfriend00, I was mistaken; in fact the 2 functions both run, in parallel, as soon as the promise is successfully resolved, and they are not chained and therefore not dependent on each other. Thanks for your help

like image 951
ElRudi Avatar asked Aug 17 '14 01:08

ElRudi


People also ask

Can I use finally without then?

finally() will not run without a then() or catch() block handling the resolution/rejection first. Any way to do this? this doesn't exactly make sense.

Why do we use then in Promise?

The then method returns a Promise which allows for method chaining. If the function passed as handler to then returns a Promise , an equivalent Promise will be exposed to the subsequent then in the method chain. The below snippet simulates asynchronous code with the setTimeout function.

What is the use of promises in angular?

Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.

What is Q defer () in AngularJS?

Simply put you can use $q. defer() to create a Promise. A Promise is a function that returns a single value or error in the future. So whenever you have some asynchronous process that should return a value or an error, you can use $q. defer() to create a new Promise.


2 Answers

Turning my comment into an answer since it seems to clear up the issue:

With your pattern, the two .then() calls on the same promise are going to get called one after another when the promise is resolved. The second .then() has only to do with the original promise and nothing to do with what happens on the first .then().

These are not chained so the second .then() has no dependency upon what is returned from the first .then() and both will be passed the same data. They are just multiple watchers of the same promise kind of like two event handlers listening for the same event.

The two .then() handlers on the same promise will be called in the order they were attached to the promise and will both be passed the same data.

See these two answers:

Is there a difference between promise.then.then vs promise.then; promise.then

Understanding javascript promises; stacks and chaining

for more info on chaining p.then(...).then(...) vs. branching p.then(...); p.then(...) with promises.

like image 71
jfriend00 Avatar answered Oct 06 '22 16:10

jfriend00


You need parallel execution: $q.all()

$q.all(
    function1,
    function2,
    function3
).then(function(responses) {
    console.log(responses);
});
like image 25
monkeyinsight Avatar answered Oct 06 '22 16:10

monkeyinsight