通过节点中的事件修改variables – 是否安全?

想象一下在节点中的这种情况:

var output = ''; module1.on('done', function() { output += 'aaaa'; }); module2.on('done', function() { output += 'bbbb'; }); // ...Doing stuff... // Assume this is inside a promise/callback and executed after both events have fired console.log(output); 

是否有可能得到像aabbaabb输出?

不可以。类似的状态可以在并发环境中由于竞争条件而发生,但是Node中的Javascript执行本质上是单线程的。 这些方法将以primefaces方式执行。

这个问题有一些很好的相关答案

话虽如此,string在大多数语言中是不可变的(因此也是线程安全的),所以像你的例子那样交错的string应该是不可能的。

  1. 使用promises等到每个模块将完成Fe http://howtonode.org/promises

  2. 在每个模块中按照精确的顺序填充variables(只是一个没有承诺的想法):

     var output = ['','']; module1.on('done', function() { output[0] = 'aaaa'; }); module2.on('done', function() { output[1] = 'bbbb'; }); // ...Doing stuff... console.log(output.join(''));