The Hapi handler function is failing to return a result

I am encountering an issue while attempting to connect hapi.js with mysql. Specifically, when defining a server route, the handler is failing to return a value.

    server.route({
    method:'GET',
    path:'/hello',
    handler:function(request,h) {

        connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
            if (error) throw error;

            console.log('The solution is: ', results[0].solution);

            return ('The solution is: ', results[0].solution)
          });

    }
});

An error message

Error: handler method did not return a value, a promise, or throw an error
is being displayed.

Despite my attempt to return

('The solution is: ', results[0].solution)
, it does not resolve the issue.

The console output shows The solution is: 2, however, an error is received in the browser.

Your help on this matter would be greatly appreciated. Thank you

Answer №1

Starting from Hapi v17, it is necessary for all route handlers to explicitly return something.

The error you are encountering indicates that you are not returning any value because the return statement is within a callback of an asynchronous function, which is separate from the main handler function.

To address this issue, you have a few options available. One approach is to convert your route handler to use async and utilize await for handling asynchronous functions like this:

handler: async function (request, h) {
  const result = await connection.query('SELECT 1 + 1 AS solution');
  return result; // manipulate the SQL result before returning it
}

Please note: This method will only work if your connection.query function returns a Promise instead of a traditional NodeJS-style callback. If it does not, you may want to consider using util.promisify to convert a callback-based function into a Promise, or wrap the function manually with new Promise.

If you prefer not to or cannot use await/async, another option is to convert the function with a callback into a Promise and then return that Promise. However, this approach can lead to nested chaining of .then() statements.

const { promisify } = require('util');

[...]

handler: function (request, h) {
  const query = promisify(connection.query);

  return query('SELECT fancy SQL')
    .then(result => {
      // process the SQL result
     return result;
    });
}

In this scenario, the final return value of your route will be the last return value within the last .then block.

Answer №2

Consider implementing async/await

server.route({
    method: 'GET',
    path: '/hello',
    handler:async function (request, h) {

        try {
            const { credentials, artifacts } = await request.server.auth.test('default', request);
            return { status: true, user: credentials.name };
        }
        catch (err) {
            return { status: false };
        }
    }
});

Answer №3

To tackle this issue, I transformed my callback function into a promise for better handling.

  handler: (request, h) => {


                return new Promise ((resolve, reject)=> {

                    connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
                         if (error) throw error;
                         console.log('The solution is: ', results[0].solution);
                         let solution = 'The solution is: ' + results[0].solution
                         let view = () => {
                             return  h.view('landing-page', {solution: solution});
                         }

                         return resolve(view())
                       });


                })


            }

My challenge lies not in the specifics of using hapi or mysql, but rather in honing my expertise in JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to declare language features in Typescript? For example, changing `!variable` to `no variable`

Can Typescript language features be declared within the app's source code? I want to enhance code clarity by implementing a small feature. Modified Null Test if (no userDetails) { // handle null } This new null test syntax is a little more conc ...

Console is displaying a Next.js error related to the file path _next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json

I keep getting an error in the console on my Next.js website. GET https://example.com/_next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json net::ERR_ABORTED 404 I'm puzzled as to why this is happening. Could it be that I'm mishandling the router? ...

Interactive window allowing the user to closely examine code

Hey guys, I need your help with something Is there a way (PHP / jQuery) that allows me to zoom in on my code? Similar to how lightbox works for images. I specifically want to zoom in on dynamic code while using Yii's CListView. I'm thinking of ...

In the process of making a request with axios in an express server

Struggling with a simple call to an API using Axios with Express, and I can't figure out why it's always pending in the browser. Here is my route: var express = require("express"); var router = express.Router(); const controller = require("../. ...

Disabling JavaScript with InternetExplorerDriver in Selenium

Is there a way to turn off JavaScript when using the InternetExplorerDriver? I've tried the code below, but it doesn't appear to disable JavaScript: self.selenium = webdriver.Remote( command_executor="http://localhost:4444/wd/hub", desire ...

Validate input JQuery only when specific radio buttons are chosen

My form currently has basic validation set up like this: <script type="text/javascript"> $(function() { $("#postform").validate({ rules: { ...

What is the best location to upload a contract in order to avoid errors from undefined methods when accessing

Attempting to execute a method from my smart contract on the ropsten test network has led me to an error within my getBalance() function: Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'methods') 46 | asy ...

Fixed Element Transitioning from Starting Position on Scroll

Check out the JSFiddle example here I'm currently working on a website utilizing Bootstrap 3. I have an image that sticks to the page when scrolling by changing its position to fixed. While this functionality works, the image tends to shift slightly ...

What is the best way to loop through a list of questions and save the answers in an array of user input?

I'm encountering a challenge with iterating through an array of questions to correctly display them on the document. The initial code snippet provided below demonstrates what I aim to accomplish without using prompts. Currently, I have set up an arr ...

Utilizing AngularJS to invoke a particular function within a PHP script: A comprehensive guide

Utilizing AngularJS to interact with a PHP script, I am aiming to specifically call out individual functions. In the provided app.js script, the updatePost and deletePost functions are triggered by button clicks. While I've successfully separated the ...

Updating parent data after filtering props in a child component: A comprehensive guide

After filtering the month in the child component, I am trying to update the data in my parent component. However, when I attempt to download excel data using vue-json-excel, the filtered month in the parent component refuses to update. I have experimented ...

Mapbox struggling with performance because of an abundance of markers

I have successfully implemented a feature where interactive markers are added to the map and respond to clicks. However, I have noticed that the performance of the map is sluggish when dragging, resulting in a low frame rate. My setup involves using NextJ ...

Modify the data in a JSON array and receive the revised array using JavaScript

Within my JSON object, I have price values in numerical format. I am looking to convert these price values into strings within the same object My approach involves using the map function: var prods = [ { "id": "id-1", "price": 239000, "inf ...

What is a reliable method to retrieve the text from the current LI if all LI elements in the list share the

I'm encountering an issue with retrieving the text from LI elements because I have 10 list items and they all have the same class name. When I attempt to fetch the text using the class name or id, I only get the text of the last item. Here is my code ...

Sending an array and an object simultaneously through a single ajax request

I previously inquired about passing an object to an ajax request for my rest service. Now I am wondering if it's possible to pass both an array and an object within a single ajax request. Any insights on this matter would be greatly valued. ...

What is preventing me from utilizing the Jquery show() method within a Div's onclick event without incorporating data-toggle="dropdown"?

I am facing an issue with a div that should act like a button. When this div is clicked, another hidden div is supposed to be displayed. However, the behavior is not as expected. I have included the data data-toggle="dropdown" attribute in the div acting a ...

How can the background of a div be altered when text is typed into an input field?

I need help with the following code. I want to be able to change the background color of a div with the class "target_bg" from red (default) to green every time someone enters or types text into the input field. <div class="target_bg"></div> & ...

retrieving the values listed on the current v-data-table page

In my vuejs2 project, I am utilizing a v-data-table to display information in columns about a large number of users. Each page shows 25 users, with a total exceeding 60,000 individuals. I am wondering if there is a way to retrieve the list of users curre ...

StartsWith() function failing when used in conjunction with takeWhile()

I'm trying to iterate over an Immutable List and create a new list containing only the entries that start with a specific string. In this case, I want to find all states that begin with the letter 'D'. However, instead of returning a list wi ...

Exploring the wonders of tokeninput with jQuery and JavaScript

After updating the code, the focus is now working. However, I'm facing a problem with getting the phone number that the user entered and placing it in front of the text in the input field called "id="some-text"? <input id="some-text" type="text" ...