Skip to content
Antoine BERNIER edited this page Mar 23, 2020 · 3 revisions

await

const to = require('await-to-js') // see https://www.google.com/amp/s/blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/amp/

app.post('/signup', async (req, res, next) => {
  const {email, password} = req.body

  //
  // 1st subrequest: check user does not already exist
  //

  {
    const [er, resp] = await to(req.uest({
      method: 'HEAD',
      url: `/api/users?email=${email}`
    }))

    if (er) {
      if (er.status === 409) {
        res.render('signup', {error: 'Email already exist'})
        return
      }

      return next(err);
    }
  }
  

  //
  // 2nd subrequest: create the user
  //

  {
    const [er, {body: user}] = await to(req.uest({
      method: 'POST',
      url: `/api/users`,
      body: {email, password}
    }))
    if (er) return next(er);
  }  

  res.redirect('/profile')
});

Clone this wiki locally