使用hapi v17
我有路线
{
method: 'GET',
path: '/redirectEbay',
handler: registerController.ebayRedirect
}
导致控制器
ebayRedirect: function ebayRedirect(request, reply) {
ebay.xmlRequest({
serviceName: 'Trading',
opType: 'GetSessionID',
appId: EBAY_CLIENT ,
devId: EBAY_DEV ,
certId: EBAY_SECRET ,
params: {
RuName: EBAY_RUNAME
}
},
function(error, data) {
console.log(data);
console.log(error);
sessionID = data.sessionID;
//catch ???
});
return (SessionID);
}
然后当然,SessionID未定义,因为它是从异步函数生成的。
尝试使用async / await:
ebayRedirect: async function ebayRedirect(request, reply) {
const session = await ebay.xmlRequest({
...
params: {
RuName: EBAY_RUNAME
}
}, function(error, data) {
sessionID = data.sessionID;
return sessionID;
});
return (session);
}
它给出了另一个错误,看起来整个处理程序被认为是格式错误,因为没有返回某些内容?
异步调用正确并返回会话
Debug: internal, implementation, error
Error: ebayRedirect method did not return a value, a promise, or throw an error
另一种具有不同品味的尝试,仍未解决,例如 await 不会等待函数解析,因为console.log会立即触发
至少摆脱了错误500 ......
也试过了一个变种:
ebayS = async function() {
console.log ( ebay() );
给出
Promise { undefined }
答案 0 :(得分:2)
ebay.xmlRequest
函数使用回调而不是promise,因此您必须将其包装在promise中:
ebayRedirect: function ebayRedirect(request, reply) {
return new Promise((resolve, reject) => ebay.xmlRequest({
params: {
RuName: EBAY_RUNAME
}
},
function(error, data) {
if (error) {
reject(error);
} else {
resolve(data.sessionID);
}
}
));
}