0

I am trying to show the JSON data into browser. When I type following code and start the server the data gets displayed in console.

const gamesDataa = gamesData(undefined, (data) => {
    console.log(data)
})

But when I try to fetch the data. like below. It shows undefined. How to get that data into an variable? So that I can pass it through handlebars and display in the browser?

const gamesDataa = gamesData(undefined, (data) => {
    return data
})

console.log(gamesDataa)

I also tried the following code. But it's sending [Object, Object] to the browser when I fetch newData in the handlebar file named /json.

app.get('/json', (req, res) => {
    
    gamesData(undefined, (data) => {
        res.render('json', {
            newData: data
        })
    })
})
  • I would read this post to understand what a callback is https://stackoverflow.com/questions/19739755/nodejs-callbacks-simple-example – gonzalo Aug 10 '20 at 15:21

1 Answers1

1

Your gonna need to create a Promise, and use asynchronous function.

const gamesDataa = async () => new Promise(res => gamesData(undefined, (data) => {
    res(data)
}));

app.get('/', async (req, res) => {
  const myData = await gamesDataa();
  res.render()// what ever you want, your data is myData;
})
Talg123
  • 1,468
  • 1
  • 10
  • 15