mern-starter icon indicating copy to clipboard operation
mern-starter copied to clipboard

add async/await functionality

Open wootsaejao opened this issue 8 years ago • 2 comments

Related issue: #203

wootsaejao avatar Oct 11 '16 11:10 wootsaejao

What about async support in the Post.Controller? I tried fighting that one and could not get it working over the weekend.

joefeser avatar Oct 11 '16 12:10 joefeser

I tried playing with server/controllers/post.controller.js (did you mean this file?)

Changing from

export function getPosts(req, res) {
   Post.find().sort('-dateAdded').exec((err, posts) => {
     if (err) {
       res.status(500).send(err);
     }
     res.json({ posts });
   });
}

Into

export async function getPosts(req, res) {
  const queryPostsAsync = () => {
    return new Promise((resolve, reject) => {
      Post.find().sort('-dateAdded').exec((err, posts) => {
        if (err) {
          reject(err);
        }
        resolve({ posts });
      });
    });
  };

  try {
    const result = await queryPostsAsync();
    res.json(result);
  } catch (err) {
    res.status(500).send(err);
  }
}

And it still doing it's job.

Here is my commit de38cc5.

wootsaejao avatar Oct 11 '16 16:10 wootsaejao