I'm not sure what sleep
is doing, but the problem in your question is happening because the callback to fs.readfile
is not an async function and the that is where await sleep(5)
is.
async function run() {
await sleep(1);
fs.readFile('list.txt', 'utf8', function (err, text) {
console.log(text); /* ^this isn't an async function */
await sleep(5);
});
}
You could make that error go away by passing an async function as a callback, however mixing promise and callback flows is not recommended and leads to problems, especially when handling errors. It prevents you from chaining the promise and catching errors from the inner await outside of run()
.
A better approach is to wrap fs.readFile()
in a promise and await that.
async function run() {
await sleep(1);
const text = await new Promise((resolve, reject) => {
fs.readFile('list.txt', 'utf8', function (err, text) {
if (err) reject(err) else resolve(text);
});
});
console.log(text);
await sleep(5);
}
This will allow you to catch any errors in much more robust way with:
run()
.then(() => /*...*/)
.catch(err => /* handle error */
and avoid unhandled rejections.