0

I have an issue with Async function with post request. I don't success to sendback a string value.

Here is the code

exports.GetQuote = async (req, res, next) => {
  try{  

   var dim = req.body.dimension;
   test = new sreq({ ** A LOT OF DATA **  })
   const data = JSON.stringify(test);
   request.post({
        headers: { 'content-type': 'application/json' },
        url: 'https://www.xxxx.com/API',
        body: data
    }, (error, res, body) => {
        if (error) {
            console.error(error)
            console.log('ERROR REQUEST');
            return
        }
          datares = JSON.parse(body);
        console.log(datares.value+" "+datares.Code); ***VALUE IS OK***
        response = datares.value+" "+datares.Code;  
        return response; *** NOT RETURN VALUE ***
    });
      }catch (e){
    console.error(e);
  }
}

the console.log is correct in nodejs console, but it dont't return the value ?

Have i missed something?

Thanks for Help

BenYsil
  • 137
  • 4
  • 16
  • Does this answer your question? [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) – Marcos Casagrande Dec 27 '19 at 17:05
  • Are you using ExpressJS? and trying to return a response to the user? – Rami Jarrar Dec 27 '19 at 17:08
  • is this a middleware or route handler? if yes you could just return `next(response);` – ROOT Dec 27 '19 at 17:13

2 Answers2

0

You are not catching the return value. You could define a variable outside the callback function.

exports.GetQuote = async (req, res, next) => {
  try{
   let response;

   var dim = req.body.dimension;
   test = new sreq({ ** A LOT OF DATA **  })
   const data = JSON.stringify(test);
   request.post({
        headers: { 'content-type': 'application/json' },
        url: 'https://www.xxxx.com/API',
        body: data
    }, (error, res, body) => {
        if (error) {
            console.error(error)
            console.log('ERROR REQUEST');
            return
        }
          datares = JSON.parse(body);
        console.log(datares.value+" "+datares.Code); ***VALUE IS OK***

        response = datares.value+" "+datares.Code;  // sets to the response var we defined above
    });
      }catch (e){
    console.error(e);
  }

  return response; // Return here
}
T. Short
  • 3,481
  • 14
  • 30
0

With an async function you pause the execution of the code so you don't have the need for a callback. Like with a phone, either you tell the other person to call you back or you await his return to the phone after he done his task you set him.

So for an async function the code can look something like that.

exports.GetQuote = async (req, res, next) => {
    try {
        // dim variable not used -- > delete
        var dim = req.body.dimension;

        test = new sreq({ /** A LOT OF DATA **/ })
        const data = JSON.stringify(test);

        // code stops running until response is here
        let response = await request.post({
            headers: { 'content-type': 'application/json' },
            url: 'https://www.xxxx.com/API',
            body: data
        })

        // error handling I can't say 
        // since I don't know what is returned here if the call should fail
        if(response){
            datares = JSON.parse(response.body);
            console.log(datares.value + " " + datares.Code);  /*** VALUE IS OK ***/
            response = datares.value + " " + datares.Code;  // sets to the response var we defined above
            return response; // Return here
        } else{
            throw new Error({msg: `something went wrong`})
        }

    } catch (e) {
        console.error(e);
    }
}

Do be aware that exports.GetQuote now hold a Promise that is implicitly returned by an async function

fubar
  • 383
  • 2
  • 11