我有以下代码:
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));
}
点击此API时,出现以下错误
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.
对于其他模型和服务,我也有类似的代码,我缺少什么?
答案 0 :(得分:2)
定义remoteMethod时,参数数量必须始终等于remoteMethod的accepts
属性中定义的参数数量加上cb
。在您的情况下,accepts
属性中定义了两个参数,因此该函数应类似于:
Orders.history = function(token, base_token, cb) {
console.log("getting history");
orderService.getHistory(token, cb)
.catch(err => cb(err));
};
我还建议您将Orders.history更改为异步函数,并完全摆脱回调。 Loopback supports async functions/promises从版本2开始。该函数可以定义如下:
Orders.history = async function(token, base_token) {
console.log("getting history");
return orderService.getHistory(token); // must return a promise
};
这可能需要您进行一些代码重构,但是它使您可以编写更简洁的代码,而不必担心所有时间都在处理异常(Loopback为异步功能提供了开箱即用的支持)。