是的Node.js“async.parallel()同步调用? [英] Is a call to Node.js' async.parallel() synchronous?

查看:147
本文介绍了是的Node.js“async.parallel()同步调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看的Node.js异步模块来解决的问题。我实现了一个小测试:

  VAR异步=要求(异步);打印功能(VAL){
    的console.log(VAL);
}async.parallel([
    功能(CB){打印(1); CB(NULL); },
    功能(CB){打印(2); CB(NULL); },
    功能(CB){打印(3); CB(NULL); },
    功能(CB){打印(4); CB(NULL); },
    功能(CB){打印(5); CB(NULL); }
]
    功能(错误){
        如果(ERR){
            console.error(ERR);
            返回;
        }
        的console.log(完成!);
    }
);的console.log(Trulu);

我可以肯定的是,Trulu日志调用将永远不会调用 async.parallel 之前调用完成?换句话说,全部的功能和Trulu日志之前被称为最后的回调要求确定?


解决方案

  

我可以肯定的是,以完成在async.parallel调用之前Trulu日志调用将永远不会被调用?


调用本身,是的。


  

在换句话说,是所有的功能


我想是这样,虽然文档没有提到它。然而,我希望没有改变,因为这很可能会破坏现有的code。


  

和Trulu日志之前被称为最后的回调要求确定?


没有。你不知道的功能,当他们是异步那么最终的回调将 Trulu 之后执行。如果所有的功能是同步的,你不应该使用异步反正。事实上,虽然async.js确实使用 setImmediate 内部所以有些回调(不幸的是难以确定)将asynchronified,但维护者的表示


  

是,使得功能异步是留给开发商


如果你想确保回调总是异步调用(后 Trulu ),即使功能是同步的,你可以考虑使用的 A +标准的承诺的。

I am taking a look at Node.js' async module to solve an issue. I have implemented a little test:

var async = require("async");

function print(val) {
    console.log(val);
}

async.parallel([
    function(cb){ print(1); cb(null); },
    function(cb){ print(2); cb(null); },
    function(cb){ print(3); cb(null); },
    function(cb){ print(4); cb(null); },
    function(cb){ print(5); cb(null); }
],
    function(err) {
        if ( err ) {
            console.error(err);
            return;
        }
        console.log("Done!");
    }
);

console.log("Trulu");

Can I be sure that the Trulu log call will never be called before the call to async.parallel is finished? In other words, are all the functions and the final callback called before the Trulu log is called for sure?

解决方案

Can I be sure that the Trulu log call will never be called before the call to async.parallel is finished?

The call itself, yes.

In other words, are all the functions

I guess so, though the docs don't mention it. I would however expect no changes, since that is likely to break existing code.

and the final callback called before the Trulu log is called for sure?

No. You don't know the functions, and when they are asynchronous then the final callback will execute after Trulu. If all the functions are synchronous, you shouldn't use async anyway. Indeed, while async.js does use setImmediate internally so some callbacks (unfortunately hard to identify) will be "asynchronified", yet the maintainer stated:

Yes, making functions asynchronous is left up to the developer

If you want to ensure that callbacks are always called asynchronously (after Trulu), even when the functions are synchronous, you might consider using A+ compliant Promises.

这篇关于是的Node.js“async.parallel()同步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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