Search code examples
node.jspromiseasync-awaithapi.js

Return from async function in hapi route


Using hapi v17


i have a route

    { 
        method: 'GET', 
        path: '/redirectEbay', 
        handler: registerController.ebayRedirect
    }

that leads to a controller

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

    }

and then of course SessionID is undefined as its generated from an async function.

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

It gives another error, looklike the whole handler is considered malformed because not returning someting ?

the async call is correct and returning the session

Debug: internal, implementation, error 
Error: ebayRedirect method did not return a value, a promise, or throw an error

Another try with a different taste, still not resolving, like the await does not wait function to resolve as console.log is triggered immediately

At least got rid of the Error 500...

enter image description here

also tried a variation :

ebayS = async function() {

console.log ( ebay() );

gives

Promise { undefined }

Solution

  • The ebay.xmlRequest function uses a callback instead of a promise, so you have to wrap it in a 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);
          }
        }
      ));
    }