title: Promises vs Async with Jsonwebtokens
body: <p>I completed a Node app tutorial and went back to rewrite the code with async/await to better learn how it's done. However I have a route handler the I can't get right without using promises:</p>
  
  <pre><code>getProfile: function(id){
      return new Promise(function(resolve, reject){
          Profile.findById(id, function(err, profile){
              if (err){
                  reject(err)
                  return
              }
  
              resolve(profile.summary())
          })
      })
  }
  </code></pre>
  
  <p>which I rewrote as:</p>
  
  <pre><code>getProfile: async (req, res, next) =&gt; {
      const profileId = req.params.id;
      const profile = await Profile.findById(profileId);
      res.status(200).json(profile)
  }
  </code></pre>
  
  <p>EDIT 2: OK i also realized I rewrote:</p>
  
  <pre><code>create: function(params){
      return new Promise(function(resolve, reject){
  
          var password = params.password
          params['password'] = bcrypt.hashSync(password, 10)
  
          Profile.create(params, function(err, profile){
              if (err){
                  reject(err)
                  return
              }
  
              resolve(profile.summary())
          })
      })
  }
  </code></pre>
  
  <p>as</p>
  
  <pre><code>newProfile: async (params, res, next) =&gt; {
      const newProfile = new Profile(params);
      const password = params.password
      params['password'] = bcrypt.hashSync(password, 10)
      const profile = await newProfile.save();
      return profile.summary()
  },
  </code></pre>
  
  <p>which could very well be causing an issue with the jsonwebtokens :&lt;</p>
  
  <p>The API endpoint I am having trouble with uses jsonwebtokens:</p>
  
  <pre><code>var token = req.session.token
      utils.JWT.verify(token, process.env.TOKEN_SECRET)
      .then(function(decode){
          return controllers.profile.getProfile(decode.id)
      })
      .then(function(profile){
          res.json({
              confirmation: 'success',
              profile: profile
          })
      })
      .catch(function(err){
          res.json({
              confirmation: 'fail',
              message: 'Invalid Token'
          })
      })
  }
  </code></pre>
  
  <p>The async code works for both the GET and POST requests to /profile route but keeps getting the 'Invalid Token' message in the API catch block. I am new to both promises and async code so Im sure theres a lot I'm not understanding right now.</p>
  
  <p>So my questions is how could I have rewritten the promise to pass off the profile object in the correct format? </p>
  
  <p>Full Files:</p>
  
  <p>controllers/ProfileController.js</p>
  
  <pre><code>var Profile = require('../models/Profile')
  var Album = require('../models/Album')
  var Promise = require('bluebird')
  var bcrypt = require('bcryptjs')
  
  module.exports = {
      index: async (req, res, next) =&gt; {
          const profiles = await Profile.find({});
          const summaries = []
          profiles.forEach(function(profile){
              summaries.push(profile.summary())
          })
          res.status(200).json(summaries)
      },
  
      newProfile: async (params, res, next) =&gt; {
          const newProfile = new Profile(params);
          const password = params.password
          params['password'] = bcrypt.hashSync(password, 10)
          const profile = await newProfile.save();
          return profile.summary()
      },
  
      getProfile: function(id){
          return new Promise(function(resolve, reject){
              Profile.findById(id, function(err, profile){
                  if (err){
                      reject(err)
                      return
                  }
  
                  resolve(profile.summary())
              })
          })
      },
  
      updateProfile: async (req, res, next) =&gt; {
          const { profileId } = req.params;
          const newProfile = req.body;
          const result = await Profile.findByIdAndUpdate(profileId, newProfile);
          res.status(200).json({success: true})
      },
  
      getProfileAlbums: async (req, res, next) =&gt; {
          const profileId = req.params.id;
          const profile = await Profile.findById(profileId);
      },
  
      newProfileAlbum: async (req, res, next) =&gt; {
          const newAlbum = new Album(req.body);
          console.log('newAlbum', newAlbum)
      }
  
  }
  </code></pre>
  
  <p>routes/profile.js:</p>
  
  <pre><code>var express = require('express');
  const router = require('express-promise-router')();
  
  const ProfileController = require('../controllers/ProfileController')
  
  router.route('/')
      .get(ProfileController.index)
      .post(ProfileController.newProfile);
  
  router.route('/:id')
      .get(ProfileController.getProfile)
      .patch(ProfileController.updateProfile);
  
  router.route('/:id/album')
      .get(ProfileController.getProfileAlbums)
      .post(ProfileController.newProfileAlbum);
  
  module.exports = router;
  </code></pre>
  
  <p>routes/account.js:</p>
  
  <pre><code>var express = require('express')
  var router = express.Router()
  var controllers = require('../controllers')
  var bcrypt = require('bcryptjs')
  var utils = require('../utils')
  
  router.get('/:action', function(req, res, next){
      var action = req.params.action
  
      if (action == 'logout'){
          req.session.reset()
          res.json({
              confirmation: 'success'
          })
      }
  
      if (action == 'currentuser'){
          if (req.session == null) {
              res.json({
                  confirmation: 'success',
                  message: 'user not logged in'
              })
  
              return
          }
  
          if (req.session.token == null) {
              res.json({
                  confirmation: 'success',
                  message: 'user not logged in'
              })
  
              return
          }
  
          var token = req.session.token
          utils.JWT.verify(token, process.env.TOKEN_SECRET)
          .then(function(decode){
              return controllers.profile.getProfile(decode.id)
          })
          .then(function(profile){
              res.json({
                  confirmation: 'success',
                  profile: profile
              })
          })
          .catch(function(err){
              res.json({
                  confirmation: 'fail',
                  message: 'Invalid Token'
              })
          })
      }
  })
  
  router.post('/register', function(req, res, next){
      var credentials = req.body
  
      controllers.profile
      .newProfile(credentials)
      .then(function(profile){
          var token = utils.JWT.sign({id: profile.id}, process.env.TOKEN_SECRET)
          req.session.token = token
          res.json({
              confirmation: 'success',
              profile: profile,
              token: token
          })
      })
      .catch(function(err){
          res.json({
              confirmation: 'fail',
              message: err.message || err
          })
      })
  })
  
  router.post('/login', function(req, res, next){
  
      var credentials = req.body
      controllers.profile
      .find({userName: credentials.userName}, true)
      .then(function(profiles){
          if (profiles.length == 0){
              res.json({
                  confirmation: 'fail',
                  message: 'Profile not found'
              })
              return
          }
          var profile = profiles[0]
  
          var passwordCorrect = bcrypt.compareSync(credentials.password, profile.password)
          if (passwordCorrect == false){
              res.json({
                  confirmation: 'fail',
                  message: 'Incorrect password'
              })
  
              return
          }
  
          var token = utils.JWT.sign({id: profile._id}, process.env.TOKEN_SECRET)
          req.session.token = token
  
          res.json({
              confirmation: 'success',
              profile: profile.summary(),
              token: token
          })
      })
      .catch(function(err){
          res.json({
              confirmation: 'fail',
              message: err
          })
      })
  })
  
  module.exports = router
  </code></pre>
  
  <p>utils/JWT.js:</p>
  
  <pre><code>var jwt = require('jsonwebtoken')
  var Promise = require('bluebird')
  
  module.exports = {
  
      sign: function(obj, secret){
          return jwt.sign(obj, secret)
      },
  
      verify: function(token, secret){
  
          return new Promise(function(resolve, reject){
              jwt.verify(token, secret, function(err, decode){
                  if (err){
                      reject(err)
                      return
                  }
  
                  resolve(decode)
              })
          })
      }
  }
  </code></pre>