Home > Mobile >  How to return a value in NodeJS inside of an Async function?
How to return a value in NodeJS inside of an Async function?

Time:07-13

I have the following code:

async function myPromiseFunction() {
  return "test";
};

function processComment(params) {
    (async () => {
          console.log(await myPromiseFunction());
    })();
}

exports.main = processComment;

The only way to output HTML code to the DOM in this case (serverless function), is through return {"body": "<h1>Test</h1>"}.

The problem is, if I put return {"body": "<h1>Test</h1>"} inside of the Async, it does not work and just does not return anything - it only works inside the processComment function whilst it is outside an async.

How can I replace console.log(await myPromiseFunction()); with return {"body": await myPromiseFunction())?

I can only console.log the value, but how can I return it so that it gets outputted as HTML?

CodePudding user response:

I think updating your processComment() method like this would do the trick. Please let me know if that doesn't work so I can update this answer :D

function processComment(params) {
    return (async () => {
          var data = await myPromiseFunction();
          return { "body": data };      
    })();
}
  • Related