1

我找不到这样做的好方法,但这是我的基本方法。它的目标是观察对象的状态,直到找到与正则表达式匹配的消息。

Cylon.waitForMessage(regex) {
  check(regex, RegExp);

  const observer = this.connections.find({
    name: 'messages'
  }).observe({
    changed: function (doc) {
      console.log(doc.lastMessage) // this is the last message to scan.
    }
  });
  let promise = new Promise((resolve, reject) => {
    // need to find the last message here and check if it matches regex
  }).then(() => observer.stop());

  return Promise.await(promise);
}

这样做的适当方法是什么?在一个 Promise 完成后,如何停止监听器或观察者?

4

1 回答 1

0

只需移动函数内部的逻辑promise

const observer = this.connections.find({
    name: 'messages'
});

let promise = new Promise((resolve, reject) => {
    observer.observe({
        changed: function(doc){
            if(regex.test(doc.lastMessage)){
               resolve(doc.lastMessage);
               observer.stop();
            }
        });
    });
  }).then((message) => doSomethingWithResolvedMessage());
于 2015-10-19T15:04:47.177 回答