我可以解雇并忘记 nodejs (ES7) 中的承诺吗? [英] Can I fire and forget a promise in nodejs (ES7)?

查看:27
本文介绍了我可以解雇并忘记 nodejs (ES7) 中的承诺吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 babel 运行这段代码:

redisClientAsync.delAsync('key');返回等待 someOtherAsyncFunction();

在没有 await 第一行的异步函数中.可以吗?

我还能如何运行我不关心的东西?

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

解决方案

是的,你可以这样做,它会并行运行两个异步函数.您刚刚创建了一个承诺并将其丢弃.

然而,这意味着当承诺被拒绝时,你不会注意到.你只会最终得到一个unhandledRejection,如果不处理它会导致你的进程崩溃.><块引用>

这样好吗?我怎么能运行我不关心的东西?

可能不行.如果你真的不关心,你一开始就没有运行它.所以你应该清楚明确你关心什么(和不关心什么):

  • 你要等吗?(副作用)
  • 你需要结果吗?
  • 你想捕捉异常吗?

如果你只想等待而不关心结果值,你可以很容易地把结果扔掉:

void (await someAsyncFunction());//或省略 void 关键字,//在表达式语句中没有区别

如果你不关心异常,你可以使用

忽略它们

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

你可以扔掉它,等待它,用它做任何事情.

如果你想要结果,你必须等待它.如果您关心异常,但又不想等待,您可能希望与以下函数并行执行:

var [_, res] = await Promise.all([someAsyncFunction(),//结果被忽略,异常不是someOtherAsyncFunction()]);返回资源;

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?

解决方案

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;

这篇关于我可以解雇并忘记 nodejs (ES7) 中的承诺吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆