0

in NodeJS I have the following code inside a function:


var request = require('request-promise');

exports.quotetest = functions.https.onRequest(async (req, res) => {


// ... code ...

await request(options, function (error, response, body) {

          const jsondata =  JSON.parse(body).response;
          

          firestore.collection('Partite').doc('Serie A').update({
            [m]  : {"home":jsondata[0].bookmakers[0]  }

        });


    })
}

And it gives me the following error: TypeError: Cannot read properties of undefined (reading 'bookmakers'). I think because when I update Firestore jsondata isn't ready yet. How could I wait for jsondata to be ready? If I try const jsondata = await JSON.parse(body).response; I receive the following error: SyntaxError: await is only valid in async functions and the top level bodies of modules

faccio
  • 652
  • 3
  • 16

1 Answers1

-1

If I try const jsondata = await JSON.parse(body).response; I receive the following error:

SyntaxError: await is only valid in async functions and the top level bodies of modules**

This does not work as it clearly states await is valid in async function, which means your JSON.parse(....) needs to be async which is not the case.

Coming to your problem: you need to give a slight delay between your function call and when response is sent Try to call the below function which gives a delay:

async function hangOn() {
  return new Promise((resolve) => setTimeout(resolve, 100));
} 

Call this function between your function call to create json data and your response like this:

await hangOn()

I recently ran into similar problem which can be referred from below thread: Call async function via PUT API call

Tyler2P
  • 2,324
  • 26
  • 22
  • 31