0

I am writing an api to get employee by id but the issue I am having is that the controller calls another function In the service and passes a parameter and callback to that function. But when the function calls the callback, I am getting an error. The code is below. I looked at online examples and tried to troubleshoot it but failed. I have a similar setup for the getall method which does not have a parameter and it seems to work fine. The code is below.

Controller code is.

  function getById(req, res, next) {
    userService.getById(req.params.id, (results) => {
      res.json(results);
        })
      .catch(err => next(err));
      }

The service code is.

 async function getById(id, callback) {database.query('SELECT * FROM employee WHERE id =' +id, (err, results) => {
       if (err) {
       callback(err);
       } else
        callback(results);
       });
      }

The error I get is:

TypeError: callback is not a function
    at Query.database.query (/user.service.js:52:7)
    at Query.<anonymous> (/Connection.js:525:10)
    at Query._callback (/Connection.js:491:16)
    at Query.Sequence.end (/Sequence.js:83:24)
    at Query.ErrorPacket (/Query.js:90:8)
    at Protocol._parsePacket (/Protocol.js:291:23)
    at Parser._parsePacket (/Parser.js:433:10)
    at Parser.write (/Parser.js:43:10)
    at Protocol.write (/Protocol.js:38:16)
    at Socket.<anonymous> (/Connection.js:91:28)
    at Socket.<anonymous> (/Connection.js:525:10)
    at Socket.emit (events.js:182:13)
    at addChunk (_stream_readable.js:283:12)
    at readableAddChunk (_stream_readable.js:264:11)
    at Socket.Readable.push (_stream_readable.js:219:10)
    at TCP.onread (net.js:639:20)
zee123
  • 73
  • 1
  • 9

1 Answers1

0

You are mixing concepts:

function getById(req, res, next) {
    UserService.getById(id)
        .then(res => console.log(res))
        .catch(err => console.error(err))
}


function getById(id) {
    return new Promise((resolve, reject) => {
        database.query('SELECT * FROM employee WHERE id =' + id, (err, results) => {
            if (err) 
                reject(err)

            resolve(results)
        });
    })
}
Dupocas
  • 20,285
  • 6
  • 38
  • 56
  • it works but for some reason when i put a console.log(id) before the return promise, it logs twice once undefined, second time with the url param. this is causing it to fail. Do you have any idea why that is happening – zee123 Jul 12 '19 at 19:19