0

I am working with express. I want to send the response as the output of an asynchronous function. Something like this:

app.get('/', (req, res) => {

  functionResponse = asynchronousFunction();
  res.send(functionResponse);

});

How do I achieve this?

tinuggunit
  • 39
  • 6
  • 1
    Please show the code for `asynchronousFunction()` because it depends upon what it's doing and what is is returning. An asynchronous result cannot be directly returned from a function in Javascript at all, no matter what you do. You can read [How do I return the response from an asynchronous function call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323) for the background. The best course of action is usually to return a promise that resolves to your value and then use `await` or `.then()` on the promise to get the result. – jfriend00 May 08 '20 at 18:50

1 Answers1

1

You can do this by using an async function. Here is the example applied to your code. It will wait for the asynchronous function to finish before continuing.

app.get('/', async (req, res) => {

  functionResponse = await asynchronousFunction();
  res.send(functionResponse);

});
Dirk V
  • 1,373
  • 12
  • 24
  • 2
    This depends upon whether `asynchronousFunction()` actually returns a promise that resolves to the final value or not. Given the level of the question, I'm not sure that would be the case here. So, this would only be once piece of a solution and insufficient by itself. – jfriend00 May 08 '20 at 18:48
  • Indeed. the asynchronousFunction actually needs to return a promise. – Dirk V May 08 '20 at 19:12