Advertisement
nubilfi

Promise rejection

Dec 13th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. [..]
  3. getUserById: (userid) => {
  4.  return new Promise((resolve, reject) => {
  5.   db.getConnection((err, connection) => {
  6.    if (err) {
  7.     return reject(err);
  8.    }
  9.  
  10.    let sql = 'SELECT * FROM users WHERE userid = ?';
  11.    let param = [userid];
  12.    sql = mysql.format(sql, param);
  13.  
  14.    connection.query(sql, (err, rows) => {
  15.     if (err) {
  16.      return reject(err);
  17.     }
  18.  
  19.     resolve(rows);
  20.     connection.release();
  21.    });
  22.   });
  23.  });
  24. }
  25. [..]
  26.  
  27. // and calling it in route file
  28. [..]
  29. const User = require('../models/user_model').CustomQueries;
  30.  
  31. router.get('/users/:userid', (req, res, next) => {
  32.  User
  33.   .getUserById(req.params.userid)
  34.   .then((rows) => {
  35.    if (rows.length === 0) {
  36.     res.json({ message: 'No user found.' });
  37.    }
  38.    res.status(200).json(rows);
  39.   })
  40.   .catch((err) => {
  41.    res.json(err);
  42.   });
  43. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement