【问题标题】:Using an await in function parameter在函数参数中使用等待
【发布时间】:2019-03-10 07:21:25
【问题描述】:

是否可以使用带参数的等待?例如:

const run = async () => {
  getStudentDetails(await getStudentId());
}

即使是这样,它似乎也可能不是最好的主意。以前有人做过吗?

【问题讨论】:

  • 这是有史以来最好的主意,我一直在这样做,这就是 await 的好处!
  • 一定要处理 promise (await) 拒绝...
  • @CodyG。以及如何处理承诺(等待)拒绝?
  • 我做到了:var pw=this.parseHex(await this.derive(password));
  • 嗯。新问题:当你调用类似 foo(await bar1(), await bar2()) 的东西时会发生什么?我假设 bar2 等到 bar1 但我懒得尝试并且从未使用过该语法

标签: javascript node.js async-await


【解决方案1】:

是的,您可以在 async function 内的每个任意上下文 (where it parses) 中使用 await 表达式,包括作为函数调用的参数。没有任何问题。

相当于

const run = async () => {
  const studentId = await getStudentId();
  getStudentDetails(studentId);
}

【讨论】:

  • 只要你和异步函数在同一个调用上下文中,例如这不起作用:async () => fnTakingCb(() => await getStudentId());
  • @ExplosionPills 是的,这不在异步函数中,在箭头函数回调中。
【解决方案2】:

是的,这会起作用,因为您可以在任何可以使用表达式的地方使用 await 关键字。

但是,为了更好的可读性(以及更好的可调试性),我更喜欢稍微更新的代码版本:

const run = async () => {
  const studentId = await getStudentId();

  getStudentDetails(studentId);
}

希望对你有帮助~

【讨论】:

    【解决方案3】:

    我一直这样做。但是,如果您想向函数传递多个参数,它们将按顺序解析。为了解决这个问题,我编写了一个 util 函数,如下所示:

    async function call(func, ...args) {
        return func(...await Promise.all(args));
    }
    
    (async function() {
            console.log(await call(functionToCall, delay(2000), delay(2000)));
    })();
    

    使用该语法 functionToCall 将在 2 秒内调用,而不是 4 秒

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2021-03-29
      • 2020-11-14
      相关资源
      最近更新 更多