在函数参数中使用等待

Jus*_*tin 13 javascript node.js async-await

是否可以将 await 与参数一起使用?例如:

const run = async () => {
  getStudentDetails(await getStudentId());
}
Run Code Online (Sandbox Code Playgroud)

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

Ber*_*rgi 11

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

它相当于

const run = async () => {
  const studentId = await getStudentId();
  getStudentDetails(studentId);
}
Run Code Online (Sandbox Code Playgroud)


Kir*_*kov 5

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

async function call(func, ...args) {
    return func(...await Promise.all(args));
}

(async function() {
        console.log(await call(functionToCall, delay(2000), delay(2000)));
})();
Run Code Online (Sandbox Code Playgroud)

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