避免有多个流的回调地狱 [英] Avoiding callback hell with multiple streams

查看:85
本文介绍了避免有多个流的回调地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当要打开多个流并且必须获得绝对的end事件以完成逻辑时,如何避免使用类似递归的结构.

How can I avoid using a recursion like structure when I got several streams to open and I have to get an absolute end event to finish the logic.

var someArray = ['file1', 'file2', 'file3'];

someArray.forEach(function( file ) {
    fs
        .createReadStream( file )
        .pipe( /* do some stuff */ )
        .on('data', function( usageInfo ) {

            // done?

        });
}

我有几个文件必须通过tp进行一些处理.如何设置一个事件,告诉我所有这些事件何时完成? 目前,我得到的是每个end事件分别.

I got several files I have to pipe through tp some processes. How can I setup an event that tells me when all of them are done? Currently what I'm getting is each end event individually.

我绝对可以同时开始每个视频流.我只需要以某种方式收集结局?

I can absolutely start each stream at the same time. I just need to somehow collect the end?

我可以为每个end事件调用一个函数调用,并对其进行计数...听起来似乎很骇人吗?...

I could invoke a function call for each end event and count it... that sounds hacky though?...

我觉得有办法兑现诺言,但我不知道怎么做.

I feel like there is a way to do this with promises but I don't know how.

推荐答案

我觉得有办法兑现诺言,但我不知道怎么做.

I feel like there is a way to do this with promises but I don't know how.

是的,有.由于promise确实表示异步值,因此您将在一个流的结尾得到一个promise:

Yes, there is. As promises do represent asynchronous values, you'd get a promise for the end of one stream:

var p = new Promise(function(resolve, reject) {
    fs.createReadStream(file)
    .on('error', reject)
    .pipe(/* do some stuff */)
    .on('end', resolve)
    .on('error', reject); // call reject(err) when something goes wrong
});

它可以像p.then(functio(usageInfo) { console.log("stream ended"); })一样使用.

现在,如果您创建多个promise,一个promise用于数组中的文件名,则所有流将并行运行,并在完成后解析其各自的promise.然后,您可以使用 Promise.all 收集-读取"await"-将从每个结果中获取的所有结果转换成一个新的承诺,以获取一系列结果.

Now if you create multiple promises, one for filename in your array, all the streams will run in parallel and resolve their respective promise when done. You then can use Promise.all to collect - read "await" - all the results from each of them into a new promise for an array of results.

var promises = ['file1', 'file2', 'file3'].map(function(file) {
    return new Promise(function(resolve, reject) {
        …
    });
});
Promise.all(promises).then(function(usageInfos) {
    console.log("all of them done", usageInfos),
}, function(err) {
    console.error("(At least) one of them failed", err);
});

这篇关于避免有多个流的回调地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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