【问题标题】:Return from async function in hapi route从 hapi 路由中的异步函数返回
【发布时间】:2018-06-22 20:36:26
【问题描述】:

使用 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 }

【问题讨论】:

  • 您还应该展示哪些尝试导致您无处可去。这听起来应该相对简单。
  • @MadaraUchiha :用更多细节更新了我的问题
  • ebay.xmlRequest 函数中可能不是问题吗?使用回调而不是承诺?

标签: node.js promise async-await hapijs


【解决方案1】:

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);
      }
    }
  ));
}

【讨论】:

  • 没有异步等待?尝试了承诺,但来自服务器的响应是空的
  • 谢谢,data.SessionID 和 sessionID 有错别字。
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 2019-12-19
  • 1970-01-01
  • 2022-08-23
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多