But if async functions return a promise, how can you explain this?
An async
function runs synchronously up to the first await
or return
(including implicit return). (When I say "up to," the synchronous part includes the operand to the right of await
or return
.) At that point (await
or return
), it returns a promise. That's so it can start whatever asynchronous process it's supposed to start. This is covered in the specification here.
Your _prefixJS
doesn't contain any await
or return
, so it synchronously runs through to the end, returning a promise that will be fulfilled with the value undefined
.
To make your async
function actually work asynchronously, you'd want to use the fs.promises
version of those functions and await
their results. Something like this (untested):
const fsp = require("fs").promises;
// ...
const _prefixJS = async file => {
console.log('running...');
await fsp.copyFile(file, `${file}.bak`);
const content = await fsp.readFile(file, 'utf8');
// Some modifications...
await fsp.writeFile(file, newContent);
console.log('stopping!');
};
With that function, the console.log('running');
call and the fsp.copyFile(...)
call are done synchronously when _prefixJS
is called, then the function returns its promise and waits for the result of fsp.copyFile(...)
before continuing its logic asynchronously.
Live example using placeholders for the fsp
functions:
const doWork = () => new Promise(resolve =>
setTimeout(resolve, Math.random() * 2000));
const fsp = {
async copyFile() {
console.log("copyFile started");
await doWork();
console.log("copyFile returning");
},
async readFile() {
console.log("readFile started");
await doWork();
console.log("readFile returning");
},
async writeFile() {
console.log("writeFile started");
await doWork();
console.log("writeFile returning");
}
};
const _prefixJS = async file => {
console.log('running...');
await fsp.copyFile(file, `${file}.bak`);
const content = await fsp.readFile(file, 'utf8');
// Some modifications...
await fsp.writeFile(file, "newContent");
console.log('stopping!');
};
console.log("calling _prefixJS");
_prefixJS()
.then(() => {
console.log("then handler on _prefixJS()");
})
.catch(error => {
console.log(`catch handler on _prefixJS(): ${error.message}`);
});
console.log("calling _prefixJS - done");