代码之家  ›  专栏  ›  技术社区  ›  Alex

所有函数都异步有什么缺点吗?[关闭]

  •  1
  • Alex  · 技术社区  · 7 年前

    较新的节点js有async await,这非常酷,因为它使代码看起来更好。

    我想知道让每个类方法异步是不是一个好主意,即使它不需要返回一个承诺?

    更清楚地说,我想这样做仅仅是为了使用酷语法。

    const database = CreateProxy('database');
    await database.something();
    

    从另一个过程。

    与一些只要求 something 从父进程

    process.send('getSomethingFromDb');
    

    在引擎盖下都使用消息传递,但第一个让它看起来不像是在表面上

    3 回复  |  直到 7 年前
        1
  •  8
  •   Estus Flask    7 年前

    Occam's razor . 没有好处,也可能有坏处。

    另一个问题是异步性具有传染性,一旦它到达模块范围, async 生活应该无处不在-因为 top-level await 尚不支持:

    module.export = (async () => {
      await require('foo');
    
      // await was accidentally dropped
      // this results in race condition and incorrect error handling
      require('foo');
      ...
    })();
    

    下面是一个使错误处理复杂化的缺点的好例子:

    async function foo() {
      throw new Error('foo');
    }
    
    async function bar() {
      try {
        return foo();
      } catch (err) {
        console.log('caught with bar');
      }
    }
    
    
    bar(); // UnhandledPromiseRejectionWarning: Error: foo
    

    尽管控制流看起来是同步的 异步 ,错误的处理方式不同。 foo try..catch 在里面 异步 功能。拒绝是不会处理的 bar

    常规函数不会发生这种情况:

    function foo() {
      throw new Error('foo');
    }
    
    function bar() {
      try {
        return foo();
      } catch (err) {
        console.log('caught with bar');
      }
    }
    
    
    bar(); // caught with bar
    

        2
  •  2
  •   Mikhail Litvinov    7 年前

    调用 async Promise ,无论函数是否实现任何异步行为。

    const asyncTest = async () => 3;
    console.log(asyncTest()); // logs 'Promise {<resolved>: 3}'
    

    因此,您必须始终确保使用 await . 但这纯粹是一个安慰的问题,即使是对你来说。但是,创建和解析承诺也会给每个函数调用增加一点时间,因此如果性能很关键,则应避免调用 大量的函数,如果可以避免的话。

        3
  •  2
  •   Orelsanpls    7 年前

    即使不需要回报承诺?

    你的代码可以工作,但我不建议这样做,原因有二:

    • 不必要的内存/cpu使用

    • 这将使你的代码难以理解。了解哪个函数是异步的或同步的对于理解系统如何工作以及它在做什么很重要。