用EventEmitter编写异步函数 [英] write async function with EventEmitter

查看:223
本文介绍了用EventEmitter编写异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是node的新手,并尝试在node中使用异步和事件行为优势.我曾经从节点上了解到,使用事件对象处理的所有内容都会异步执行.
然后,我尝试了此操作,请考虑以下代码:

I am new in node and try to use async and event behavior advantages in node. I used to understand from node, everything that handle with Event object, it gonna be async execution.
Then i had try this, consider following code:

var events = require("events");

var event = new events.EventEmitter();


event.on("work", function () {

    for (var i = 0; i <= 10; i++) {
        console.log("I do my work " + i);
    }

    event.emit("done");
});

var async = function (cb) {

    event.on("done", cb);
    event.emit("work");
    for (var i = 0; i <= 10; i++) {
        console.log("Async " + i);
    }
}


async(function () {
    console.log("I am done callback!");
});  

这是异步执行?我认为不!为什么,因为我已经读过很多这句话:

This is async execution? In my opinion no! Why, because i had read this sentence many:

一个事件被触发了,所以去做点什么,然后在完成后,来 回来告诉我,但与此同时我还要做些其他的事情.

An event is fired, so go and do something and then when you have finished it, come back and tell me, but in meanwhile i will do something else.

就像快餐店一样.但是上面的代码,当事件工作触发时,将发生以下顺序:

Like a fast food restaurant scenario. But the code above, when the event work gonna fired, following sequence will happen:

  1. 进入回调
  2. 通过循环
  3. 输出我正在做我的工作
  4. 触发完成事件
  5. 输出我已完成回调!
  6. 输出异步n

为什么我要完成回叫!要在异步n之前输出?为什么这里不像快餐店那样,像

why I am done callback! gonna output before Async n? Why is here not like fast food restaurant scenario, like

工作事件被解雇了,去找你塞东西,然后在你回来的时候回来 完成后,与此同时,我将输出Async n

the work event is fired, go and do you stuff and come back when you done, in meanwhile i will output Async n

这是我用来了解事件驱动行为和节点中异步的信息.但是现在我很困惑.我知道,javascript在单线程上工作.如何使用事件发射器编写异步函数?但是我认为这是不可能的,因为当我发出一个事件时,它将立即执行处理程序.

This is i used to understand about event driven behavior and async in node. But now i am very confused. I know, javascript works on single thread. How can i write an async function with event emitter? But i think is not possible, because when i emit an event, it will immediately execute the handler.

推荐答案

我以前从节点上了解事件处理的所有内容 对象,它将异步执行.

I used to understand from node, everything that handle with Event object, it gonna be async execution.

这是不正确的.事件是同步的.添加侦听器时,您只是将回调保存在对象中:

This is incorrect. Events are synchronous. When you add a listener, you're just saving the callback in an object:

this._events[type].push(listener);

发出事件时,您只是在迭代一个数组并调用每个侦听器:

When you emit an event, you're just iterating an array and calling each listener:

for (i = 0; i < len; i++)
      listeners[i].apply(this, args);

源代码: https://github.com/joyent/node/blob/master/lib/events.js

这是异步执行?我认为不!

This is async execution? In my opinion no!

您是正确的.如果您调用任何I/O函数或使用setImmediatenextTick或计时器,则它是异步的-否则,它是同步的.异步编写的同步代码不会将其转换为异步代码.

You are correct. It's async if you call any I/O function or use setImmediate, nextTick or a timer—otherwise, it's synchronous. A synchronous code being written asynchrously doesn't convert it to an asynchrous code.

为什么我要完成回叫!要在异步n之前输出?

why I am done callback! gonna output before Async n?

因为收到完成"回调,所以您调用"cb":

Because when you receive the "done" callback you call to "cb":

event.on("done", cb);

cb返回时,将执行异步n"循环.

When cb returns, the "Async n" loop is executed.

如何使用事件发射器编写异步函数?

How can i write an async function with event emitter?

使用setImmediateprocess.nextTick.

如果要推迟执行我做我的工作"循环,可以将events.emit ("work")行换成nextTick.

If you want to postpone the "I do my work" loop execution, you can wrap the line events.emit ("work") with nextTick.

var events = require("events");

var event = new events.EventEmitter();


event.on("work", function () {

    for (var i = 0; i <= 10; i++) {
        console.log("I do my work " + i);
    }

    event.emit("done");
});

var async = function (cb) {

    event.on("done", cb);
    process.nextTick (function () {         //<-----
        event.emit("work");
    });                                     //<-----
    for (var i = 0; i <= 10; i++) {
        console.log("Async " + i);
    }
}


async(function () {
    console.log("I am done callback!");
});  

这将打印:

Async 0
Async 1
Async 2
Async 3
Async 4
Async 5
Async 6
Async 7
Async 8
Async 9
Async 10
I do my work 0
I do my work 1
I do my work 2
I do my work 3
I do my work 4
I do my work 5
I do my work 6
I do my work 7
I do my work 8
I do my work 9
I do my work 10
I am done callback!

这篇关于用EventEmitter编写异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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