1

I currently have a project which makes use of native Promises. I am looking to migrate these Promises over to Async/Await. I am having troubles migrating them over; I am trying to follow this article. Below is the current code with the Promises which need changing to Async/Await.

routes.js

// Importing user information
import user from '../server-controllers/user';

// User Information Route
router.get('/about', (req, res) => {
  user.profile().then((data) => {
    return res.render('user', {
      title: data,
    });
  }).catch((e) => {
    res.status(500, {
      error: e,
    });
  });
});

user.js

/*
This file contains any server side modules needed.
*/

module.exports = {
// Returns information about a user
  profile: () => {
    return new Promise((resolve, reject) => {
      const user = "John Doe";
      resolve(user);
    });
  },
};

If there is any help in what I would need to do to convert these that would be helpful. I don't know if the code needs changing on either the routes or user file (or both).

The error which I am getting in my terminal is [object Error] { ... }

2
  • Here's a whole app with async / await: github.com/bryanmacfarlane/sanenode Commented Jul 29, 2017 at 2:12
  • Just replace every then call by await. Commented Jul 29, 2017 at 2:31

1 Answer 1

4

The key thing to remember about async and await is that an async function is really just a function that returns a Promise, and lets you use await to resolve Promises. So when a Promise rejects, if it is awaited then you will get an error thrown in the context of wherever the await is.

So technically, if you want to use async/await syntax, you don't need to change user.js. You could just change routes.js to:

// Importing user information
import user from '../server-controllers/user'

// User Information Route
router.get('/about', async (req, res) => {
  try {
    const data = await user.profile()
    return res.render('user', {
      title: data
    })
  } catch (error) {
    // Runs if user.profile() rejects
    return res.status(500, {error})
  }
})

But user.js is made more succinct when you use an async function:

module.exports = {
  // Returns information about a user
  // This returns a Promise that resolves to 'John Doe'
  profile: async () => 'John Doe'
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.