我可以在nodejs(ES7)中开火并忘记承诺吗?

发布于 2025-02-07 10:40:04 字数 233 浏览 3 评论 0原文

我想用babel运行此代码:

redisClientAsync.delAsync('key');
return await someOtherAsyncFunction();

在没有的异步函数内,等待第一行。可以吗?

我还能如何运行我不在乎的东西?

我可以在没有回调的情况下触发非弹药函数del('键',null)吗?

I would like to run this code with babel:

redisClientAsync.delAsync('key');
return await someOtherAsyncFunction();

inside an async function without await the first line. is this OK?

how else can I run something that I don't care?

Can I just fire the non-promisified function del('key',null) without a callback?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

舞袖。长 2025-02-14 10:40:05

是的,您可以做到这一点,它将并行运行两个异步功能。您刚刚创造了一个诺言并将其抛弃。

但是,这意味着当拒绝承诺时,您将不会注意到。您只需获取Unhandledledeptivection最终,如果不处理,这将使您的流程崩溃。

可以吗?我如何运行我不在乎的东西?

可能还不好。如果您真的不在乎,您就不会首先运行它。因此,您应该清楚和明确您关心的东西(以及不关心):

  • 您想等待吗? (对于副作用)
  • 您需要结果吗?
  • 您想捕获例外吗?

如果您只想等待并且不在乎结果值,则可以轻松地丢弃结果:

void (await someAsyncFunction()); // or omit the void keyword,
                                  // doesn't make a difference in an expression statement

如果您不在乎例外,可以使用它们忽略它们

… someAsyncFunction().catch(function ignore() {}) …

,可以扔掉,等待它,对它。

如果您想要结果,则必须等待它。如果您关心异常,但不想真正等待,则可能需要与以下功能并行执行:

var [_, res] = await Promise.all([
    someAsyncFunction(), // result is ignored, exceptions aren't
    someOtherAsyncFunction()
]);
return res;

Yes, you can do that, and it will run the two asynchronous functions in parallel. You've just created a promise and thrown it away.

However, this means that when the promise is rejected you won't notice. You'll just get an unhandledRejection eventually which will crash your process if not handled.

Is this OK? How can I run something that I don't care?

Probably it's not OK. If you truly wouldn't care, you hadn't run it in the first place. So you should be clear and explicit what you care about (and what not):

  • do you want to wait? (for side effects)
  • do you need the result?
  • do you want to catch exceptions?

If you only want to wait and don't care for the result value, you can easily throw away the result:

void (await someAsyncFunction()); // or omit the void keyword,
                                  // doesn't make a difference in an expression statement

If you don't care about exceptions, you can ignore them using

… someAsyncFunction().catch(function ignore() {}) …

You can throw that away, await it, do anything with it.

If you want the result, you have to await it. If you care about exceptions, but don't really want to wait, you may want to execute it in parallel with the following functions:

var [_, res] = await Promise.all([
    someAsyncFunction(), // result is ignored, exceptions aren't
    someOtherAsyncFunction()
]);
return res;
诗笺 2025-02-14 10:40:05

在异步函数内部无需等待第一行。可以吗?

是的,在某些情况下,您想这样做是完全合理的。特别是在您不关心结果的情况下 - 一个例子是一个分析跟踪操作,不应干扰业务关键代码。

我还能如何运行我不在乎的东西?

在许多方面,但是简单地调用承诺功能有效。在这种情况下,您的del没有回调的情况可能会起作用,但是有些功能不会防止不传递回调,因此您可以传递空功能(.del('key',((( )=> {}))。

但是,您确实想确保您知道即使您不想破坏代码的操作 - 因此,请考虑添加process.on.on(“ unhandledledsection' ,事件处理程序明确忽略这些特定异常或通过

redisClient.delAsync('key').catch(()=>{});

以下方式抑制它们:

redisClient.delAsync('key').catch(logErr);

inside an async function without await the first line. is this OK?

Yes, there are cases where you'd want to do this which are perfectly reasonable. Especially where you don't care about the result - one example is an analytics tracking operation that should not interfere with business critical code.

how else can I run something that I don't care?

In many ways, however simply calling the promise function works. Your del without a callback would probably work in this case but some functions don't guard against not passing callbacks, so you can pass an empty function instead (.del('key', () => {})).

You do want to however make sure that you know about it failing, even if you don't want to disrupt the operation of code - so please consider adding a process.on("unhandledRejection', event handler to explicitly ignore these particular exceptions or suppress them via:

redisClient.delAsync('key').catch(()=>{});

Or preferably, something like:

redisClient.delAsync('key').catch(logErr);
失去的东西太少 2025-02-14 10:40:05

不在node.js中

节点不要等待持续未决的承诺。如果其他任务已经完成并且事件循环中没有任何剩余的任务,则即使存在未决的承诺,节点过程也将被终止。

对于以下脚本,如果一些hotherasyncfunction()在5秒内得到解决,但是redisClientAsync.delasync('key')需要10秒钟才能执行,则节点进程将被终止从理论上讲5秒后,在第一行解析之前

async function doSomething() {
  redisClientAsync.delAsync('key');
  return await someOtherAsyncFunction();
}

await doSomething();

Not in Node.js.

Node does not wait for ever-pending Promises. If other tasks are already completed and there is nothing left in the event loop, the Node process will be terminated even though there exists pending promise.

For the following script, if someOtherAsyncFunction() get resolved in 5 seconds, but redisClientAsync.delAsync('key') takes 10 seconds to execute, the Node process will be terminated after 5 seconds in theory, before the first line is resolved.

async function doSomething() {
  redisClientAsync.delAsync('key');
  return await someOtherAsyncFunction();
}

await doSomething();
匿名的好友 2025-02-14 10:40:05

从我到目前为止所做的所有研究中,我认为这样做是可以的,只要您保证您不是的功能,等待 保证 一种方式如果发生这种情况,请处理自己的错误。例如,try-catch包装整个功能主体,就像您在以下片段中看到的asyncfunction一样。

该函数是同步或异步投掷的都没关系。它保证您的mainfunction 无论如何都将完成。那是这里的关键。

如果您不保证这一点,则必须冒险:

  • 如果它同步投掷,那么您的主要功能将无法完成。
  • 如果它异步地抛出,您将获得一个未手持的辩护
// THIS IS SOME API CALL YOU DON'T WANT TO WAIT FOR

const mockAPI = () => {
  console.log("From mockAPI");
  return new Promise((resolve,reject) => {
    setTimeout(() => reject("LATE THROW: API ERROR"), 500);
  });
};

// THIS IS THE SOME ASYNC FUNCTION YOU CALL BUT NOT AWAIT FOR

const asyncFunction = async (syncThrow) => {
  try {
    console.log("Async function START");
    if (syncThrow) throw new Error("EARLY THROW");
    await mockAPI();
    console.log("Async function DONE");
  }
  catch(err) {
    console.log("From async function catch");
    console.log(err.message || err);
    return;
  }
};

// THIS IS YOUR MAIN FUNCTION

const mainFunction = async (syncThrow) => {
  try {
    console.clear();
    console.log("Main function START");
    asyncFunction(syncThrow);
    console.log("Main function DONE <<< THAT'S THE IMPORTANT PART");
  }
  catch(err) {
    console.log("THIS WILL NEVER HAPPEN");
    console.log(err);
  }
};
<div>
  <button onClick="mainFunction(true)">Sync throw</button>
  <button onClick="mainFunction(false)">Async throw</button>
</div>

From all the research I've made so far, I think it's fine to do it, as long as you guarantee that the function you are not awaiting for guarantees a way to handle its own errors in case that happens. For example, a try-catch wrapping the whole function body, like you see in the following snippet for the asyncFunction.

It doesn't matter if the function throws synchronously or asynchronously. It guarantees the your mainFunction will complete no matter what. That's the key point here.

If you don't guarantee that, you have to risks:

  • If it throws synchronously, your main function will not complete.
  • If it throws asynchronously, you'll get an unhandled excepction

// THIS IS SOME API CALL YOU DON'T WANT TO WAIT FOR

const mockAPI = () => {
  console.log("From mockAPI");
  return new Promise((resolve,reject) => {
    setTimeout(() => reject("LATE THROW: API ERROR"), 500);
  });
};

// THIS IS THE SOME ASYNC FUNCTION YOU CALL BUT NOT AWAIT FOR

const asyncFunction = async (syncThrow) => {
  try {
    console.log("Async function START");
    if (syncThrow) throw new Error("EARLY THROW");
    await mockAPI();
    console.log("Async function DONE");
  }
  catch(err) {
    console.log("From async function catch");
    console.log(err.message || err);
    return;
  }
};

// THIS IS YOUR MAIN FUNCTION

const mainFunction = async (syncThrow) => {
  try {
    console.clear();
    console.log("Main function START");
    asyncFunction(syncThrow);
    console.log("Main function DONE <<< THAT'S THE IMPORTANT PART");
  }
  catch(err) {
    console.log("THIS WILL NEVER HAPPEN");
    console.log(err);
  }
};
<div>
  <button onClick="mainFunction(true)">Sync throw</button>
  <button onClick="mainFunction(false)">Async throw</button>
</div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文