0

in index.js i run my node server and in datainput.js i want to get the data from the function putdata which return the confirmed cases to server but unfortunately it shows undefined inside index.js index.js

const express = require('express')
const fs = require('fs')
const got = require('got')
const cheerio = require('cheerio')
const datainput = require(__dirname + '/datainput.js')
const idea = require(__dirname + '/idea.js')

const app = express()

app.get('/', function(req, res) {
  const vgmUrl =
    'https://news.google.com/covid19/map?hl=en-IN&gl=IN&ceid=IN%3Aen&mid=%2Fm%2F03rk0'
  console.log(datainput.putdata(vgmUrl, 'data'))
  // console.log(datainput.putdata(vgmUrl,"data"));
  res.send('bad luck turns it to good')
})

app.listen(4000, function() {
  console.log('server runs on port 4000...........')
})

datainput.js here i have a function pudata where i have retuened a data but in index.js it show undefined where i have console.log it

const fs = require('fs')
const got = require('got')
const cheerio = require('cheerio')

function putdata(vgmUrl, filename) {
  var confirmed
  var recoverd

  got(vgmUrl)
    .then(response => {
      const $ = cheerio.load(response.body)
      confirmed = $('.qs41qe .UvMayb').text()
      return confirmed
    })
    .catch(err => {
      console.log(err)
    })
}
exports.putdata = putdata
hgb123
  • 13,869
  • 3
  • 20
  • 38
  • 1
    You're not actually returning anything from `putdata()`. Your return statement is inside an asynchronous callback so the return value goes back to that callback and the function has long since returned already with no stated return value before you even have the value. See [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323) for more info. – jfriend00 Jul 04 '20 at 06:49
  • 2
    In your case, you should put a `return` in front of `got(...).then()` and then when you call `putdata()` elsewhere, you will get a promise and the caller can use `await` or `.then()` to get the value. – jfriend00 Jul 04 '20 at 06:58

0 Answers0