是否有惯用的方式来表达“if (c1 || c2)"?在 JavaScript 中,当一个条件是承诺而另一个不是? [英] Are there idiomatic ways to express "if (c1 || c2)" in JavaScript when one of the conditions is a promise and the other is not?

查看:33
本文介绍了是否有惯用的方式来表达“if (c1 || c2)"?在 JavaScript 中,当一个条件是承诺而另一个不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我仅在满足各种条件时才执行算法中的后续步骤时,我会这样表达:

When I only perform the next steps in my algorithm if various conditions are met I express it this way:

if (sc1 || sc2) {
  do();
  various();
  things();
}

当我只根据承诺的履行执行后续步骤时,我可以这样表达:

When I only perform the next steps based on the fulfillment of a promise I can express it like this:

asyncCheck().then(ac1 => {
  if (ac1) {
    do();
    various();
    things();
  }
}

当条件 sc1 只是一个常规的旧同步表达式但条件 ac2 通过承诺异步出现时,我如何用惯用的 JavaScript 表达?

How can I express in idiomatic JavaScript when condition sc1 is a just a regular old synchronous expression but condition ac2 comes asynchronously via a promise?

假设原生 ES6 承诺和非平凡代码在满足条件时被执行.

Assume native ES6 promises and nontrivial code that gets executed if the conditions are met.

例如,这种明显"的方式看起来很丑:

For instance, this "obvious" way seems ugly:

if (sc1) {
  do();
  various();
  things();
} else {
  asyncCheck().then(ac2 => {
    if (ac2) {
      do();
      various();
      things();
    }
  }
}

我可以将重复的代码放在一个以任何方式调用的函数中,这样不那么难看,但我觉得我可能会遗漏一些其他 JavaScript 程序员可能正在使用的更惯用的东西.

I could put the repeated code in a function that gets called either way, which is less ugly, but I feel like I could be missing something more idiomatic that other JavaScript programmers might be using.

我也应该添加这个观察:因为在我的情况下,有一个逻辑或,它应该短路,所以如果简单检查已经false,它不应该打扰缓慢的延迟检查.

I should add this observation too: Since in my case, there is a logical or, it should short circuit so it shouldn't bother with the slow deferred check if the simple check is already false.

推荐答案

其实很简单:

Promise.resolve(sc1 || asyncCheck()).then(cond => {
  if (cond) {
    do();
    various();
    things();
  }
});

诚然,sc1 的真实性可能会被评估两次,否则就会短路.您也可以使用

Admittedly the truthiness of sc1 is possibly evaluated twice, but otherwise it does short-circuit. You can also use

(sc1 ? Promise.resolve(true) : asyncCheck()).then(cond => { … });

这篇关于是否有惯用的方式来表达“if (c1 || c2)"?在 JavaScript 中,当一个条件是承诺而另一个不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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