Frage

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!

War es hilfreich?

Lösung

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.

Andere Tipps

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);
       });
    });
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top