简体   繁体   中英

How to loop on queue of promises (serialize async messages)

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);
       });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM