-1

Following is my code where I have a nodejs Google function, and I am invoking a REST API. But in below code snippet, I get the response, but need to get response out of try-catch so I can do further processing.

exports.postFunction = (req, res) => {

    try{
        fetch('https://someapi', {
            method: 'post',
            body: JSON.stringify(req.body),
            headers: {'Content-Type': 'application/json'},
        })
        .then(res => res.json())
        .then(json => console.log("****"+JSON.stringify(json)));
      }
      catch(err) {
        console.error("999999999"+err);
      }
    console.log("Here I should be able to get response of the invoked rest api");

}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
codedup
  • 1
  • 1
  • 5
    Possible duplicate of [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) – CertainPerformance May 11 '19 at 12:49

1 Answers1

0

Create a variable and assign the response.

exports.postFunction = (req, res) => {

   var response;

   try{
        fetch('https://someapi', {
          method: 'post',
          body: JSON.stringify(req.body),
          headers: {'Content-Type': 'application/json'},
         })
         .then(res => res.json())
         .then(json => response = JSON.stringify(json)); // like this
   }
   catch(err) {
     console.error("999999999"+err);
   }
   console.log("Here I should be able to get response of the invoked rest api");

} 
Darshana Pathum
  • 649
  • 5
  • 12
  • Thanks, I did that, but when I do console.log(response), after the catch I get "undefined". That is why this is strange. – codedup May 11 '19 at 21:48