stefanlz
stefanlz

Reputation: 287

Angular JS: processing promises in order (without chaining)

This is similar to question 17757654, but without chaining.

Background:
I have a very chatty API which brings back some JSON every key press, and sometimes these requests come back in the wrong order (with very fast key presses). Chaining promises seems like a reasonable solution, but I was wondering if there is a nice way to solve this without chaining? (and without knowing any details about the request/message)

I've written an example using timeouts here: http://jsfiddle.net/zakGh/

and below,

var myModule = angular.module('myModule', []);
myModule.factory('HelloWorld', function ($q, $timeout) {

    var getSlowFirstMessage = function () {
        var deferred = $q.defer();

        $timeout(function () {
            deferred.resolve('Slow First Message');
        }, 2000);

        return deferred.promise;
    };

    var getFastSecondMessage = function () {
        var deferred = $q.defer();

        $timeout(function () {
            deferred.resolve('Fast Second Message');
        }, 1000);

        return deferred.promise;
    };

    return {
        getSlowFirstMessage: getSlowFirstMessage,
        getFastSecondMessage: getFastSecondMessage
    };

});

myModule.controller('HelloCtrl', function ($scope, HelloWorld) {

    $scope.messages = [];

    HelloWorld.getSlowFirstMessage().then(function (message) {
        $scope.messages.push(message);
    });

    HelloWorld.getFastSecondMessage().then(function (message) {
        $scope.messages.push(message);
    });

});

<body ng-app="myModule" ng-controller="HelloCtrl">
     <h1>Messages</h1>

    <ul>
        <li ng-repeat="message in messages">{{message}}</li>
    </ul>
</body>

Upvotes: 1

Views: 2298

Answers (1)

Jonathan Rowny
Jonathan Rowny

Reputation: 7588

I'd use Queue from the async library found here: https://github.com/caolan/async#queue

If you set the concurrency to 1, it just does it all in series. Check out the example

myModule.controller('HelloCtrl', function ($scope, HelloWorld, $timeout) {

$scope.messages = [];   

var q = async.queue(function (task, callback) {
    task().then(function(message){
        $timeout(function(){
            $scope.messages.push(message); 
            callback();
        });
    });
}, 1);


// assign a callback
q.drain = function() {
    console.log('all items have been processed');
}

// add some items to the queue

q.push(HelloWorld.getSlowFirstMessage, function (err) {
   console.log('finished processing slow');
});
q.push(HelloWorld.getFastSecondMessage, function (err) {
   console.log('finished processing fast');
});

});

Here's the working fiddle: http://jsfiddle.net/zakGh/4/

Upvotes: 2

Related Questions