I have a queue of promises (representing msgs) which I need to process in order. I'm using angularJS.

For the sake of the example suppose I have connect() which returns a promise for the connection and then msgQueue which is a JavaScript array of promises, each representing a msg.

I would start by doing this:

connect().then(function(){
    return msgQueue.dequeue();
});

// Async Loop on all msgs... How?

I'm sort of a Defer/Promise newbie so bear with me.

Thanks!

有帮助吗?

解决方案

function serializeAsynch(queue,operate) {
  var msg = queue.dequeue();
  if (msg) msg.then(function(data) { operate(data); serializeAsynch(queue); });
}

connect().then(function() { serializeAsynch(msgQueue,process); });

I think that will work. We're waiting for connect to resolve, then passing in the msgQueue. We get the first message in the queue and set it's resolution handler to process the data and then recurse on the queue. The recursion will dump out when there's nothing left in the queue.

其他提示

Something like this would work. Assuming that msgQueue.dequeue() returns a promise.

function doWork(work) {
    work().then(function(data) {
       //process data
       msgQueue.dequeue().then(function(work) {
           doWork(work);
       });
    });
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top