Home > Software design >  NodeJS, how to return value from request call to main function?
NodeJS, how to return value from request call to main function?

Time:12-28

I have the following code written. How do I return html from the request block when data is available into main viewPage function?

const request = require('request');

let viewPage = (url) => {
    request({url:url,headers:headers,method:'GET'},(error,response,html) => {
        let stockStatus = null;
        if(!error && response.statusCode == 200) {
           //...return html variable from here
        } else {

        }
      });

      return html
}

It returns empty/null when I call result = viewPage(URL) because data has not arrived yet.

CodePudding user response:

Similar result using Axios.

const axios = require('axios').default;

async function viewPage(url, headers = {}) {
    const response = await axios({
        method: 'get',
        url: url,
        headers: headers
    });
    return response?.data;
}

async function run() {
    const pageData = await viewPage("URL");
    return console.log(pageData);
}

CodePudding user response:

API request call is async, you are not waiting for that to finish.

var rp = require("request-promise");

let viewPage = (url) => {
  return rp({ uri: url, headers: headers, method: "GET" })
    .then(function (html) {
      // Do something or check
      return html;
    })
    .catch(function (err) {
      console.log(err);
      return err;
    });
};

async function some() {
  var result = await viewPage(URL);
}
  • Related