0

I want to run my function as I wrote it, but as we know node.js is asynchronous language, so the code in the run in an async manner here my problem starts in my code I want to execute each line of code in the sequence of as they write.

Now my question is that how to run a function sequentially in Node.js.

Here is my code of index.js file where i calling function

var request = require('request');
var requestHandling = require('../routes/request_handling_functions');

router.get("/example1", function (req, res) {

var result = 
 requestHandling.requestMethodGet('http://localhost:8083/getUserInfo/865c2c25-d9e7-412d-a064-326bd66c9e9c', res);
    console.log("===RESULT=====");
    console.log(result);
});

in above code I want to call the requestMethodGet function first, and after that, I want to console the result of that function. but whole things went wrong it executes the console.log lines first then it calls the function.

My output in the console is

===RESULT=====
undefined

Here is my file in which i define that function

var request = require('request'); var log = require('log4js').getLogger("index");

module.exports = {
requestMethodGet: async function (url, res) {

    //SET ALL THESE PARATMETER TO MAKE REQUEST
    request.get({url: url}, function (e, r, body) {

        var errorResult = module.exports.validateResponseeData(e);

        console.log("====errorResult===in===Get==method====");
        console.log(errorResult);
        if (errorResult != "continue") {
            console.log("===im in not continue");
            res.send(errorResult);
        } else {

            //LOGING THE RESPONSE BODY
            log.info('body:', body);

            var responseData = JSON.parse(body);


console.log("======AUTHTOKEN=========DATA=====================");
            console.log('error:', e);
            console.log('statusCode:', r && r.statusCode);
            console.log('body:', body);
            console.log("====================================");
            console.log(responseData);

            res.send(responseData);
        }
    });
}

if any help is needed regarding this question or wants more information, then please inform me.

user979879
  • 93
  • 1
  • 10

1 Answers1

-5

You can create your async function as promise function and then make it can be accessed sequentially using async await and try catch method javascript.

You can see this information for better information https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Luthfi
  • 274
  • 4
  • 12