【问题标题】:Maintaining state across asynchronous events in javascript在 javascript 中跨异步事件维护状态
【发布时间】:2017-01-21 13:50:41
【问题描述】:

我们有一个基于事件监听器的加载器。这是通过 pouchdb。

因此,每当客户端收到文档时,侦听器就会触发。我们检查该文档是否与加载器相关,然后在另一个异步回调之后更新 UI 全局变量中的百分比。

现在问题来了

  1. 从服务器收到响应并将监听器添加到事件队列中
  2. 从服务器收到另一个响应,并将侦听器添加到事件队列中
  3. 为第一个事件队列元素调用 eventListener 方法
  4. doAsyncCallbackithVerification 被添加到事件队列中
  5. 为第二个事件队列元素调用 eventListener 方法
  6. doAsyncCallbackithVerification 被添加到事件队列中
  7. 调用doAsyncCallbackithVerification方法,百分比更新为85
  8. 调用doAsyncCallbackithVerification方法,百分比再次更新为85

当我们期望百分比为 90 时(因为方法调用次数为 2 和 2 * 5)


var percentage = 80;
function eventListener() {
  if(loaderRelated){
    doAsyncCallbackithVerification(percentage, function(newPercentage){
      percentage = newPercentage;
    });
  }
}

db.listenForTheEvents(eventListener);

处理此问题的正常标准是什么,请记住我上面写的内容是基于当时更复杂情况的 javascript 伪代码。我们还使用 RxJs,因此可以使用它来缓解这些情况,如果可以的话,如何使用。

【问题讨论】:

  • 我不清楚你想要发生什么。第二个回调是否应该将百分比更改为不同的数字?
  • 是的,这将是预期的输出,我还稍微编辑了伪代码以传递状态值。那么给定的预期输出将是 90。

标签: javascript events asynchronous callback rxjs


【解决方案1】:

由于您只提供了伪代码,因此很难给出准确的答案,但这是关于我将如何使用 RxJS:

const listenToDb = Observable.fromCallback(db.listenForTheEvents);  // in RxJS5 it's 'bindCallback'
const asyncCbWithVerif = Observable.fromCallback(db.doAsyncCallbackWithVerification);  // in RxJS5 it's 'bindCallback'

const fetchPercentage$ = listenToDb()
    .filter(event => isLoaderRelated(event))      // don't propagate any unrelated events
    .switchMap(event => asyncCbWithVerif(event))  // if some new event arrives, the switchMap will automatically cancel the last call of 'asyncCbWithVerif'
    .do(newPercentage => console.log(newPercentage));

fetchPercentage$.subscribe(); // or however you wish to activate the stream, maybe publish & share, maybe replay, ect...

【讨论】:

    【解决方案2】:

    我只需向事件处理程序传递一个百分比以添加到已完成的总数中。在伪代码中匹配您的问题:

    var percentage = 80;
    function eventListener() {
      if(loaderRelated){
        doAsyncCallbackithVerification(percentage, function(percentageCompleted){
          percentage += percentageCompleted;
        });
      }
    }
    
    db.listenForTheEvents(eventListener);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多