ekhan
ekhan

Reputation: 251

Multiple call to async functions

If I call an async function multiple times that is changing the state of memory will I need a lock. e.g. If I am calling fs.writeFile multiple times in my code like

fs.writeFile('test.txt', 'data', function(err){});
fs.writeFile('test.txt', 'data', function(err){});

how will I ensure that there are no synchronization issues? Are there any locking mechanism?

Upvotes: 1

Views: 77

Answers (1)

jfriend00
jfriend00

Reputation: 707228

There aren't any "locking" mechanisms for this type of issue in Javascript. Instead, you respond to the completion of asynchronous operations and put the operations that you want to come afterwards in that callback.

If you want to make sure these two commands happen in the proper sequence, then you can and should manually sequence them:

fs.writeFile('test.txt', 'data1', function(err){
    // presumably some other code here
    fs.writeFile('test.txt', 'data2', function(err){});        
});

Though, I assume this a simplified example because there's no reason to write one piece of data as a file and then immediately write a different piece of data as the entire file. So, there must normally be some intervening code.

Upvotes: 1

Related Questions