最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to use await in a callback? - Stack Overflow

matteradmin6PV0评论

My code is:

async function run() {
  await sleep(1);
  fs.readFile('list.txt', 'utf8', function (err, text) {
    console.log(text);
    await sleep(5);
   });
}

run();

await sleep(1) is fine, but await sleep(5) results in:

SyntaxError: async is only valid in async function

Is fs.readFile the problem? How do I use await in such a situation?

The above is a reduced example to test. In my actual usage, I need to put the await sleep in a callback deeply nested inside a few more asynchronous functions.

My code is:

async function run() {
  await sleep(1);
  fs.readFile('list.txt', 'utf8', function (err, text) {
    console.log(text);
    await sleep(5);
   });
}

run();

await sleep(1) is fine, but await sleep(5) results in:

SyntaxError: async is only valid in async function

Is fs.readFile the problem? How do I use await in such a situation?

The above is a reduced example to test. In my actual usage, I need to put the await sleep in a callback deeply nested inside a few more asynchronous functions.

Share Improve this question asked Aug 12, 2018 at 3:30 u936293u936293 16.4k34 gold badges121 silver badges222 bronze badges 4
  • 1 It is about the third parameter you pass to readFile, which is a function. It has to be async too since you use await inside that function. – kennyzx Commented Aug 12, 2018 at 3:35
  • 1 Try adding async before function inside readFileparameters like this: fs.readFile('list.txt', 'utf8', async function (err, text) ... – Yashar Aliabbasi Commented Aug 12, 2018 at 3:35
  • The callback function of the fs.readFile() is not async function. await could be used in only async function. – Andrew Li Commented Aug 12, 2018 at 3:39
  • Are you sure you posted the correct error message? – Code-Apprentice Commented Aug 12, 2018 at 4:03
Add a ment  | 

4 Answers 4

Reset to default 4

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 remended 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.

The above is a reduced example to test. In my actual usage, I need to put the await sleep in a callback deeply nested inside a few more asynchronous functions.

Callback based APIs shouldn't be augmented with async..await or promises in general when there is a chance to stick to promises (may not be possible if a callback is called more than once). This results in poor control flow and error handling.

Once there is async callback function inside run, it's impossible to chain nested promise with run().then(...). Errors from nested promises may remain unhandled as well and result in UnhandledPromiseRejectionWarning.

The proper way is to move from callbacks to promises and use promise control flow. Generally this can be achieved with promise constructor:

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);
}

There are numerous ways to get promises from Node callback based APIs, e.g. fs provides promise API since Node 10:

async function run() {
  await sleep(1);
  const text = await fs.promises.readFile('list.txt', 'utf8');
  console.log(text);
  await sleep(5);
}

If your function includes an "await", you must prefix your function declaration with "async".

NOTE: By making your function an "async" function a promise is always returned. So if you return a string, that string will get automatically wrapped in a Promise object.

You can therefore return a Promise manually (for clarity). A simple resolved promise is sufficient:

async function foo(){
    await bar();
    return Promise.resolve('optional'); // optionally resolve with a value
}

The keyword "async" always goes before the keyword "function":

var foo = async function(){
    await bar();
    return Promise.resolve('optional'); // optionally resolve with a value
}

... and well for arrow functions:

var foo = sally( async () => {
    await bar();
    return Promise.resolve('optional'); // optionally resolve with a value
})

To retrieve the return value:

foo().then(val => console.log(val) ); // prints "optional" to console

You have to use aysnc key before function start. await keyword will not work with normal function.

async function run() {
  await sleep(1);
  fs.readFile('list.txt', 'utf8', async function (err, text) {
    console.log(text);
    await sleep(5);
   });
}

run();
Post a comment

comment list (0)

  1. No comments so far