简体   繁体   English

如何在异步函数内部的 NodeJS 中返回一个值?

[英]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>"} .在这种情况下(无服务器函数)将 HTML 代码输出到 DOM 的唯一方法是通过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 .问题是,如果我将return {"body": "<h1>Test</h1>"}放在 Async 内部,它就不起作用,只是不返回任何东西 - 它只在processComment函数内部起作用,而它是async之外。

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

I can only console.log the value, but how can I return it so that it gets outputted as HTML?我只能console.log的值,但我怎样才能返回它以便它作为 HTML 输出?

I think updating your processComment() method like this would do the trick.我认为像这样更新您的processComment()方法可以解决问题。 Please let me know if that doesn't work so I can update this answer :D如果这不起作用,请告诉我,以便我可以更新这个答案:D

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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