Queue promises

I use mbostock / queue for queues without asynchronous operation. This is more for speed limitation (the user interface generates several events where the backend can process it slowly), and also to make sure that they are processed sequentially. I use it as

function request(d, cb) { //some async oper add.then(function(){ cb(null, "finished ") }) } var addQ = queue(1); addQ.defer(request) //called by few req at higher rates generated by UI 

I already use angular.js $ q for async to work. So, do I need to use mbostock/queue , or can I build a queue from $q (which is in the spirit of https://github.com/kriskowal/q )

Thanks.

+6
source share
3 answers

Basic $ q chain example

Yes, you can chain with Angular $ q! The following is an example showing how recursion can be used to create a queue of any length. Each message occurs sequentially (one after another). The second post will not start until the first post is over.

This can be useful when writing to databases. If the database does not have its own backend queue, and you make several records at the same time, you may find that not all of your data is saved!

I added the Plunkr Example to demonstrate this code in action.

 $scope.setData = function (data) { // This array will hold the n-length queue var promiseStack = []; // Create a new promise (don't fire it yet) function newPromise (key, data) { return function () { var deferred = $q.defer(); var postData = {}; postData[key] = data; // Post the the data ($http returns a promise) $http.post($scope.postPath, postData) .then(function (response) { // When the $http promise resolves, we also // resolve the queued promise that contains it deferred.resolve(response); }, function (reason) { deferred.reject(reason); }); return deferred.promise; }; } // Loop through data creating our queue of promises for (var key in data) { promiseStack.push(newPromise(key, data[key])); } // Fire the first promise in the queue var fire = function () { // If the queue has remaining items... return promiseStack.length && // Remove the first promise from the array // and execute it promiseStack.shift()() // When that promise resolves, fire the next // promise in our queue .then(function () { return fire(); }); }; // Begin the queue return fire(); }; 

You can use a simple function to start a turn. For the sake of this demonstration, I pass an object full of keys to a function that will separate these keys into separate messages, and then POST them to the Henry HTTP Post Dumping Server . (Thanks Henry !)

 $scope.beginQueue = function () { $scope.setData({ a: 0, b: 1, /* ... all the other letters of the alphabet ... */ y: 24, z: 25 }).then(function () { console.log('Everything was saved!'); }).catch(function (reason) { console.warn(reason); }); }; 

Here is a link to the Plunkr Example if you want to try this code.

+3
source

The short answer is no, you do not need an additional library. Promise.then () is fairly atomic. Long answer: it is worth making the queue () function to save the DRY code. Bluebird-promises seems pretty complete, but something here is based on AngularJS $ q.

If I were doing .queue (), I would like it to handle errors.

Here's the angular factory service and some use cases:

 /** * Simple promise factory */ angular.module('app').factory('P', function($q) { var P = $q; // Make a promise P.then = function(obj) { return $q.when(obj); }; // Take a promise. Queue 'action'. On 'action' faulure, run 'error' and continue. P.queue = function(promise, action, error) { return promise.then(action).catch(error); }; // Oook! Monkey patch .queue() onto a $q promise. P.startQueue = function(obj) { var promise = $q.when(obj); promise.queue = function(action, error) { return promise.then(action).catch(error); }; return promise; }; return P; }); 

How to use it:

 .run(function($state, YouReallyNeedJustQorP, $q, P) { // Use a $q promise. Queue actions with P // Make a regular old promise var myPromise = $q.when('plain old promise'); // use P to queue an action on myPromise P.queue(myPromise, function() { return console.log('myPromise: do something clever'); }); // use P to queue an action P.queue(myPromise, function() { throw console.log('myPromise: do something dangerous'); }, function() { return console.log('myPromise: risks must be taken!'); }); // use P to queue an action P.queue(myPromise, function() { return console.log('myPromise: never quit'); }); // Same thing, but make a special promise with P var myQueue = P.startQueue(myPromise); // use P to queue an action myQueue.queue(function() { return console.log('myQueue: do something clever'); }); // use P to queue an action myQueue.queue(function() { throw console.log('myQueue: do something hard'); }, function() { return console.log('myQueue: hard is interesting!'); }); // use P to queue an action myQueue.queue(function() { return console.log('myQueue: no easy days'); }); 
+1
source

Chained Promises

The Angular $q implementation allows you to chain promises, and then handle the permissions of these promises according to your own logic. The methods are slightly different from mbostock/queue , but the intent is the same. Create a function that determines how your deferral will be done (creating a promise), then make them available to a higher-level controller / service for specific resolution processing.

Angular uses $q.defer() to return promise objects, which can then be called in the order you want in your application logic. (or even missed, mixed up, intercepted, etc.).

I will throw away some code, but I found this 7 minute video on egghead.io to be the best short demo: https://egghead.io/lessons/angularjs-chained-promises and this will make FAR better for explanation. Thomas (the host) builds a very small dashboard application that queues weather and flight data, and processes this queue when the user asks for their name. ThomasBurleson/angularjs-FlightDashboard

I will create a smaller demonstration on koded using the food-in-restaurant situation to demonstrate this concept: http://codepen.io/LongLiveCHIEF/pen/uLyHx

Code examples here:

https://gist.github.com/LongLiveCHIEF/4c5432d1c2fb2fdf937d

0
source

All Articles