排队承诺

Queuing promises(排队承诺)

本文介绍了排队承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 mbostock/queue 对少数异步操作进行排队.更多的是速率限制(UI 生成的事件很少,后端可以缓慢地处理它),并确保它们按顺序处理.我喜欢用它

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 are processed sequentially. I use it like

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

我已经使用 angular.js $q 进行异步操作.那么,我是否必须使用 mbostock/queue,或者我可以用 $q 构建一个队列(本质上是 https://github.com/kriskowal/q)

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

谢谢.

推荐答案

基本的$q链示例

是的,你可以使用 Angular 的 $q! 构建一个链式队列!这是一个示例,向您展示如何使用递归来创建任意长度的队列.每个帖子都是连续发生的(一个接一个).在第一个帖子完成之前,第二个帖子不会开始.

Basic $q Chain Example

Yes you can build a chained queue using Angular's $q! Here is an example that shows you how you could use recursion to create a queue of any length. Each post happens in succession (one after another). The second post will not start until the first post has finished.

这在写入数据库时​​会很有帮助.如果数据库后端没有自己的队列,而你同时进行多次写入,你可能会发现你的数据并没有全部保存!

This can be helpful when writing to databases. If the database does not have it's own queue on the backend, and you make multiple writes at the same time, you may find that not all of your data is saved!

我添加了一个 Plunkr 示例来演示此代码的实际应用.

I have added a 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();
};

您可以使用一个简单的函数来开始您的队列.为了演示,我将一个充满键的对象传递给一个函数,该函数将这些键拆分为单独的帖子,然后将它们发布到 Henry 的 HTTP 后转储服务器.(感谢亨利!)

You can use a simple function to begin your queue. For the sake of this demonstration, I am passing an object full of keys to a function that will split these keys into individual posts, then POST them to Henry's 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);
  });
};

如果您想尝试一下,这里是 Plunkr 示例的链接代码.

Here is a link to the Plunkr example if you would like to try out this code.

这篇关于排队承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:排队承诺

基础教程推荐