简体   繁体   中英

Calling async function in node.js

I have an async function

async function getPostAsync() {
  const post = await Post.findById('id');

  // if promise was successful,
  // but post with specific id doesn't exist
  if (!post) {
    throw new Error('Post was not found');
  }

  return post;
}

I am calling the function with

app.get('/', (req, res) => {
  getPostAsync().then(post => {
    res.json({
      status: 'success',
    });
  }).catch(err => {
    res.status(400).json({
      status: 'error',
      err
    });
  })
});

but I just receive

{
  "status": "error",
  "err": {}
}

I would expect to either get the error Post was not found or some error with the connection or something like that, but the variable err is simply an empty object in my catch statement.

Consider the following:

let e = Error('foobar');
console.log( JSON.stringify(e) )

This outputs {} , much like in your case. That's because errors don't serialize to JSON very well.

Instead, try this:

res.status(400).json({
  status : 'error',
  err    : err.message // `String(err)` would also work
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM