Queuing promises

前端 未结 3 1752
抹茶落季
抹茶落季 2020-12-31 17:24

I use mbostock/queue for queuing few async operation. It is more to rate limit (UI generate few events, where the backend can process it slowly), and also to make sure they

3条回答
  •  攒了一身酷
    2020-12-31 17:49

    The short answer is no, you don't need an extra library. Promise.then() is sufficiently "atomic". The long answer is: it's worth making a queue() function to keep code DRY. Bluebird-promises seems pretty complete, but here's something based on AngularJS's $q.

    If I was making .queue() I'd want it to handle errors as well.

    Here's an angular service factory, 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'); });
    

提交回复
热议问题