Reputation: 4750
I have the following code:
Orders.js
'use strict';
var OrderService = require('../services/OrderService');
module.exports = function(Orders) {
var orderService = new OrderService(Orders);
Orders.history = function(data, cb) {
console.log("getting history");
orderService.getHistory(data, cb)
.catch(err => cb(err));
};
Orders.remoteMethod('history', {
http: { verb: 'get', path: '/:token/history' },
accepts: [
{ arg: "token", type: "string", required: true },
{ arg: "base_token", type: "string", required: true }
],
returns: { type: 'object', root: true }
});
};
Orderservice.js
function OrderService(Orders){
}
OrderService.prototype.getHistory = async function(token, baseToken, callback){
<some operation>
callback(null, this.validatorService.finalize(buyResult));
}
When I hit this API, I get the following error
node:1996) UnhandledPromiseRejectionWarning: TypeError: cb is not a function
at orderService.getHistory.catch.err (/usr/app/server/models/orders.js:12:18)
at processTicksAndRejections (internal/process/next_tick.js:81:5)
(node:1996) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
| (node:1996) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have similar code for other models and services, what am I missing?
Upvotes: 1
Views: 3875
Reputation: 1275
When you define a remoteMethod the amount of arguments must always be equal to a number of arguments defined in the accepts
property of your remoteMethod plus one which is cb
. In your case there are two arguments defined in the accepts
property, so the function should look like:
Orders.history = function(token, base_token, cb) {
console.log("getting history");
orderService.getHistory(token, cb)
.catch(err => cb(err));
};
I would also recommend you to change your Orders.history to an async function and move away from callbacks completely. Loopback supports async functions/promises starting from version 2. The function can be defined as following:
Orders.history = async function(token, base_token) {
console.log("getting history");
return orderService.getHistory(token); // must return a promise
};
It may require a bit of code refactoring on your side but it allows you to write a cleaner code and you do not have to worry about the exceptions handling all the time (Loopback supports it out of the box for async functions).
Upvotes: 4