Return 来自 hapi 路由中的异步函数
Return from async function in hapi route
使用 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 是未定义的,因为它是从异步函数生成的。
尝试异步/等待:
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 }
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);
}
}
));
}
使用 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 是未定义的,因为它是从异步函数生成的。
尝试异步/等待:
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 }
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);
}
}
));
}