This question already has an answer here:
I know that those methods area still synchronous, but that's not the topic. I'm currently going from synchronized nodejs-methods to async ones. I am just asking that if async methods return a promise, how is it that it runs before the end
console.log statement.
I'm a bit confused about async functions. It says that they return a promise. A promise usually does not immediately run before the rest of the code, because javascript works with the "run to completion" approach.
But if async functions return a promise, how can you explain this?
const _prefixJS = async file => {
console.log('running...')
fs.copyFileSync(file, `${file}.bak`);
const content = fs.readFileSync(file, 'utf8');
// Some modifications...
fs.writeFileSync(file, newContent);
console.log('stopping!')
};
console.log('start')
_prefixJS(f);
console.log('end')
// Output: start > running... > stopping! > end
In my opinion, the output should be: start > end > starting... > stopping!
Because promises run concurrently and they are placed at the end of the event loop.