【问题标题】:Array.push() doesn't affect outer .then scopeArray.push() 不影响外部 .then 范围
【发布时间】:2021-05-04 13:42:51
【问题描述】:

第一次获取请求后的 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)

标签: javascript node.js fetch-api


【解决方案1】:

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

由于您有一个异步操作循环并且它们都可以并行运行,我建议使用.map() 来遍历循环并为您构建承诺的输出数组,然后使用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;
  });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2017-12-02
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多