处理输入事件,排队,并逐个调用异步函数

时间:2017-04-09 20:46:00

标签: javascript firebase

我有以下代码:

database.ref('chats/').on('child_added',(snapshot) => {
  this.addMessage(snapshot.val());
})

我在更新服务器数据库时收到消息事件。然后我需要如何确保并行调用addMessage?

2 个答案:

答案 0 :(得分:0)

You can push Promise or function which return Promise to an array. If current Promise or function which returns Promise is not defined, call first function in array queue, chain .then() to schedule call to same function when current asynchronous operation completes, where next item in queue is next item in array, else call function when queue array .length is 0.

window.onload = () => {

  const [queue, input, div] = [
    Array()
  , document.querySelector("input")
  , document.querySelector("div")
  ];
  
  let curr;

  const complete = message => {
    curr = void 0;
    console.log(`message: ${message}, queue.length: ${queue.length}`);
  };

  const processData = data => div.innerHTML += data;

  const checkQueue = (message = "done") =>  
    curr() // `curr()` if pass function to `queue`, `curr` if pass `Promise`
    .then(processData)
    .then(() => (curr = queue.shift()) ? checkQueue(message) : message)   

  const handleMessage = value => {
    queue.push(
      // push function to call that returns `Promise`
      // or push `Promise`, remove `() =>`,
      // include `()` after `curr` at `checkQueue`
      () => new Promise(resolve => 
              setTimeout(() => {
                resolve(value);
              }, Math.floor(Math.random() * 1500))
            )
    );
    if (!curr) {
      curr = queue.shift();
      checkQueue("complete")
      // do stuff when `queue` `.length` is `0`
      .then(complete);
    }
  }

  input.oninput = () => {
    console.log(input.value.slice(-1));
    handleMessage(input.value.slice(-1));
  }

}
<input type="text" />
<div></div>

Where this.addMessage() returns Promise or a function which returns a Promise

database.ref('chats/').on('child_added',(snapshot) => {
  handleMessage(this.addMessage(snapshot.val()));
});

答案 1 :(得分:0)

由于您的意见,我找到了一个简单的解决方案:

    var queue = Promise.resolve();
    database.ref('chats/' + this.props.alarm.date).on('child_added',
    (snapshot) => {
      queue =  queue.then(()=> {
        this.addMessage(snapshot.val());
      });
    });