2

Imagine this scenario in node:

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);

Is it possible to ever get output like aabbaabb?

1
  • thread-safe by default, because javascript is called by 1 thread. Now let's think about webworker? Commented Dec 15, 2013 at 19:37

2 Answers 2

2

No. Similar states can occur as a result of race conditions in concurrent environments, but Javascript execution in Node is inherently single-threaded. The methods will execute atomically.

This question has some excellent relevant answers

Having said that, strings are immutable (and therefore inherently thread safe) in most languages so interleaved strings like your example should be impossible anyway.

Sign up to request clarification or add additional context in comments.

Comments

0
  1. Use promises to wait until every module will finish F.e. http://howtonode.org/promises

  2. In every module fill variable by speecified order like (just an idea without promises):

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

1 Comment

Thank you for the response. Regarding [1], the modules need to run in parallel, I should have clarified that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.