nodejs:event.on是异步?

时间:2017-09-20 14:21:20

标签: node.js events javascript-events event-handling

我正在阅读这篇文章:write async function with EventEmitter

下面这段代码是异步吗?

var event = new events.EventEmitter();
event.on("done", cb);

1 个答案:

答案 0 :(得分:0)

在给定的代码中,您正在订阅活动。当您调用event.emit("done")时,节点按照订阅的顺序执行给定的回调。

实施例

    var event = new events.EventEmitter();

    event.on("done",() => {
        console.log(("notified 1"))
    });

    event.on("done",() => {
        setImmediate(() => {
            console.log("async")
        });
        console.log(("notified 2"))
    });

    event.on("done",async () => {
        console.log(("notified 3"))
    });

    console.log("before firing an event");

    event.emit("done");

    console.log("after firing an event");

输出

before firing an event
notified 1
notified 2
notified 3
after firing an event
async