如何在 async/await 之后记录 return 值?

How to log return value after async/await?

下面是我粘贴的 PoC 代码,我删除了很多行,但它显示了我面临的 problem/question。

createPost() returns ret 变量中的“post 数字”。除了记录它之外,我不需要“post 号码。

对于当前的实现,我必须在 while 循环之外定义 ret,并且由于顺序代码在 NodeJS 事件循环中的异步代码之前是 运行,我希望日志记录将在 createPost() 之前执行,这不是我想要的。

问题

是否可以在执行 createPost() 时仅记录 ret

module.exports = async (p) => {
  let ret = 0;

  try {

    while (true) {

      switch (x) {
        case 1:
          isOk = await getStatusCode({ ... });
          break
        case 2:
          isOk = await getString({ ... });
          break
        default:
          throw "";
      };

    ret = await createPost(p);
    appLogger.info(`Created post: ${ret}`);   // I don't need 'ret' for anything else than logging it

  } catch (error) {
    appLogger.error(error);
  }
}

createPost.js

const axios = require('axios');

module.exports = async (c) => {
  try {
    const r = await axios({ ... });
    return r.data.key;
  } catch (error) {
    throw new Error(JSON.stringify(error.response.data, null, 2));
  };

};

...and since sequential code is run before asynchronous code in the NodeJS event loop, I expect the logging will be executed before createPost(), which is not what I want.

第一个 await 之后的 async 函数中的所有代码都是异步的,而不是同步的。在您的代码中,appLogger.info 调用不会发生,直到 createPost 完成 其工作(异步)。

所以没有必要在循环外声明ret(即使上面不是真的,那也没什么用),你可以直接做内联,见*** 评论:

module.exports = async (p) => {
  // *** No `ret` here

  try {

    while (true) {

      switch (x) {
        case 1:
          isOk = await getStatusCode({ ... });
          break
        case 2:
          isOk = await getString({ ... });
          break
        default:
          throw "";
      };

    const ret = await createPost(p); // *** Declare it here
    appLogger.info(`Created post: ${ret}`);

  } catch (error) {
    appLogger.error(error);
  }
}

代码在 await 处异步等待,只有在 createPost 完成后才继续。

这是一个简化的例子:

const randomDelay = () => new Promise(resolve => {
    setTimeout(resolve, Math.floor(Math.random() * Math.floor(Math.random() * 300) + 500));
});

async function doSomethingElse() {
    await randomDelay();
}

async function createPost(i) {
    await randomDelay();
    return i * 2;
}

async function example(max) {
    console.log("Starting (this log is synchronous)");
    for (let i = 0; i < max; ++i) {
        await doSomethingElse();
        const ret = await createPost(i);
        console.log(`i = ${i}, ret = ${ret}`);
    }
    console.log("All done");
}

console.log("Calling example");
example(5)
.then(() => {
    console.log("example promise fulfilled");
})
.catch(error => {
    console.error("example promise rejected", error);
});
console.log("Done calling example, it's running asynchronously");


技术上,你根本不需要ret,这也行得通:

appLogger.info(`Created post: ${await createPost(p)}`);

但如果是我,我会保留上面第一个代码块中所示的内容。更容易调试。