异步方法的串行执行
程序员文章站
2022-07-15 14:56:41
...
eventeimter
用于简单处理两个事件的串行执行,在事件A执行完成之后,执行函数B。
const events = require('events');
const fs = require('fs');
const emitter = new events.EventEmitter();
fs.readFile('../file1.txt','utf-8',function (err,content) {
emitter.emit('file1',content);
});
emitter.on("file1",function (content) {
console.log(content);
})
eventproxy
eventproxy可以用于监听多个事件的执行结果,在事件全部执行完成之后,再操作所有的结果。
//(reafFile1,readFile2)->all()
const EventProxy = require('eventproxy');
const fs = require('fs');
const ep = new EventProxy();
ep.all("file1","file2",function (file1,file2) {
console.log(file1);
console.log(file2);
});
fs.readFile('../file1.txt','utf-8',function (err,content) {
ep.emit('file1',content);
});
fs.readFile('../file2.txt','utf-8',function (err,content) {
ep.emit('file2',content);
});
step
step实现事件之间的串行操作,通过this变量在事件之间传递结果。
// readFile1->readFile2->done
const step = require('step');
const fs = require('fs');
step(
function readFile1(){
fs.readFile('../file1.txt','utf-8',this);
},
function readFile2(err,content) {
console.log('readFile2:');
console.log(content);
fs.readFile('../file2.txt','utf-8',this);
},
function done(err,content) {
console.log('content:');
console.log(content);
}
);
推荐阅读