Array.push() 不影响外部 .then 作用域

Array.push() doesn't affect outer .then scope

第一次获取请求后 lambda 函数的第二部分:

.then((articles) => {
  var images = [];
  for (let i = 0; i < articles.length; i++) {
    fetch(
      `example.com/${articles}`
    )
      .then((image) => image.json())
      .then((image) => {
        images.push([
          image["parse"]["title"],
          image["parse"]["images"][
            Math.floor(Math.random() * image["parse"]["images"].length)
          ],
        ]);
        console.log(images); \ logs expected
      });
  }
  console.log(images); \ logs empty array
  return images;
})

.push() 如何改变外部 images 变量?

它确实会影响外部作用域数组。在循环中的异步操作完成之前,您只是在执行 console.log(images)。

因为你有一个异步操作循环,它们都可以 运行 并行,我建议使用 .map() 遍历循环并为你构建 promises 的输出数组,然后使用Promise.all() 等待所有这些承诺完成并按顺序收集所有结果。你可以这样做:

.then((articles) => {
  return Promise.all(articles.map(article => {
      return fetch(`http://example.com/${article}`)
        .then(image => image.json())
        .then(image => {
            return [
            image.parse.title,
            image.parse.images[
              Math.floor(Math.random() * image["parse"]["images"].length)
          ];
        });
  })).then(allImages => {
      // this .then() handler is only here to we can log the final result
      console.log(allImages);
      return allImages;
  });
})