1

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?

0

1 Answer 1

1

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.

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

Comments

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.