0

I have the following code that gets an input from a form in my index.html file and then POSTs it to the node script that is running at localhost:8080. The node script then takes the input and queries it by calling the LUIS.ai API and then sends the response back. However the response is taking a long time to show up and I have to refresh the page and confirm form submission to get the results. Is there a more efficient way to do this. I am new to Node.js.

app.js

//Modules
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var http = require('http');

//Variables and definitions
var app = express();
var query = null;
//LUIS.ai URL
var luisURL = "LUIS_API_URL";
var intent = null;

//body-parser
app.use(bodyParser.urlencoded({ extended: true })); 

//Get and handle LUIS.ai data
function getLUISData(urlLUIS){
    //Get LUIS.ai JSON data
    request({url:urlLUIS, json:true}, function (error, response, body) {
        intent = body
    });
    return intent;
}

//Get query from HTML form
app.post('/query', function(request, response) {
    query = request.body.query;
    luisURL = luisURL.concat(encodeURIComponent(query));
    var data = getLUISData(luisURL);
    response.send(data);
});

app.listen(8080);

index.html

<!DOCTYPE html>
<html>
<body>
    <form action="http://127.0.0.1:8080/query" method="post">
        <input type="text" name="query"/>
        <input type="submit" value="Submit" />
    </form>
</body>
</html>
Nikhil Raghavendra
  • 1,570
  • 5
  • 18
  • 25

1 Answers1

1

Use promises to handle asynchronous. You can read more about promise here

 function getLUISData(urlLUIS){
        //Get LUIS.ai JSON data
     return new Promise((resolve, reject) => {
        request({url:urlLUIS, json:true}, function (error, response, body) {
            if (err) return reject(err);
            try {
                resolve(body);
            } catch(e) {
                reject(e);
            }
        });//end of request

  });//end of promise
}

app.post('/query', function(request, response) {
    query = request.body.query;
    luisURL = luisURL.concat(encodeURIComponent(query));
    getLUISData(luisURL).then(function(data){ // execution will wait here until request completes. here promise gives you data. 
         response.send(data);
    });
});
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40