简体   繁体   English

如何在承诺队列上循环(序列化异步消息)

[英]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. 我有一个需要处理的promise队列(代表msg)。 I'm using angularJS. 我正在使用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. 就本例而言,假设我有connect() ,它为连接返回一个promise,然后是msgQueue ,它是JavaScript的promise数组,每个数组代表一个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. 我有点像Defer / Promise新手,所以请多多包涵。

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 . 我们正在等待connect解析,然后传入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. 我们获得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. 假设msgQueue.dequeue()返回一个promise。

function doWork(work) {
    work().then(function(data) {
       //process data
       msgQueue.dequeue().then(function(work) {
           doWork(work);
       });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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