等待异步事件处理程序的设计模式 [英] Design pattern for waiting on asynchronous event handlers

查看:228
本文介绍了等待异步事件处理程序的设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有我的应用程序的地方,一个对象应该发出一个事件,应该延迟执行,直到所有事件处理程序已经完成的工作。在事件处理程序可能会被执行异步操作(例如写入数据库)。

There are places in my application where an object should emit an event and should delay execution untill all event handlers have completed work. The event handlers might be performing an asynchronous operation (e.g. writing to database).

Application.on("login", function(evt) {
    // Asynchronous operation (e.g. update info in database)
});

Application.trigger("login").then(function() {
    // Execute stuff after all (async) event handlers are done
});

我环顾四周,并没有发现这方面的任何既定的设计模式。我已经得到了我很高兴与实现,但我很好奇,如果有人已经解决了这个不同?

I've looked around and haven't found any established design patterns for this. I've got an implementation I'm happy with, but I'm curious if anyone has solved this differently?

推荐答案

我的解决方案是将承诺[] 属性添加到 EVT 参数。异步事件回调只是一个承诺到这个阵列和 triggerAsync 函数返回一个承诺,等待所有承诺来解决。

My solution is to add a promises[] property to the evt argument. Asynchronous event callbacks simply add a promise to this array and the triggerAsync function returns a promise that wait on all the promises to settle.

http://jsfiddle.net/nonplus/9aCC4/

执行(使用骨干事件和jQuery的承诺,而应为其他堆栈工作,太):

Implementation of the triggerAsync method (using Backbone events and jQuery promises, but should work for other stacks, too):

// Trigger an event and return promise that waits on
// event handler promises
function triggerAsync(emitter, name, evt) {
    evt || (evt={});
    evt.promises = [];
    emitter.trigger(name, evt);
    return $.when.apply(null, evt.promises);
}

triggerAsync的用法:

triggerAsync(obj, "myEvent").then(function() {
    // Code executed after event handlers are done
});

异步事件处理程序的执行情况:

// Async handler doing an ajax request
obj.on("myEvent", function (evt) {
    evt.promises.push($.ajax(...));
});

// Async handler doing generic async operation
obj.on("myEvent", function (evt) {
    var dfd = $.Deferred();
    evt.promises.push(dfd.promise());

    // Async operation
    // Eventually calls dfd.resolve() or dfd.reject()
});

这篇关于等待异步事件处理程序的设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆