简体   繁体   中英

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

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?

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 };      
    })();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM