Return 来自 page.click() 回调的单个元素数组

Return an array of single element from page.click() callback

这里来自 document for page.click() for Puppeteer:

 const [response] = await Promise.all([
  page.waitForNavigation(waitOptions),
  page.click(selector, clickOptions),
]);

因为只有一个return值response,我不太明白为什么不是下面这样:

 const response = await Promise.all([
  page.waitForNavigation(waitOptions),
  page.click(selector, clickOptions),
]);

有人会阐明这个声明吗?

这与 Promise.all 的工作方式有关,而不是与人偶操纵有关。

Promise.all: [...] the returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values).

这意味着 await Promise.all(...) returns 一个包含两个 Promise 结果的数组。现在让我们看看这两个 Promise 实现了什么:

因此await Promise.all([ ... ])将得到一个数组,第一个值为主要资源响应,第二个值为未定义。

多亏了 destructuring assignment 我们可以这样写:

const [response, valueWhichWillBeUndefined] = await Promise.all([ ... ]);

由于我们对第二个值不感兴趣,我们可以将该变量排除在外(因为我们知道它将未定义)导致:

const [response] = await Promise.all([ ... ]);