首页 > 解决方案 > 为什么在循环内执行 Promise 时对象数组变为空

问题描述

下面的代码将返回 [{}]

下面的代码有什么问题?

 fileId.forEach((element) => {
        getFileFromCloud(element)
            .then((result) => {
                console.log(result);
                x.v.push({ dataUrl: result });
            })
            .catch((err) => {
                console.log(err.message);
            });
    });

标签: node.js

解决方案


您可以生成一个 Promise 列表,然后执行 Promise.all 来获取结果数组。

我建议使用 async/await 语法从 Promise.all 调用中获取结果,我相信这更具可读性。

你也可以做 Promise.all(promises).then(resultList => .....

这可用于填充 xv 数组。

const fileId = [0,1,2,3];
const x = {
 v: []
};

async function getFileFromCloud(element) {
    return { fileId: element, data: "some data" };
}

async function testDownload() {
  let promises = fileId.map((element) => {
       return getFileFromCloud(element)
              .then((result) => {
                  return ({ dataUrl: result });
              })
              .catch((err) => {
                  console.log(err.message);
                  throw err; // Throw to keep promise chain intact.
              });
  });

  let resultList = await Promise.all(promises);
  // Append to the x.v array.
  x.v = x.v.concat(resultList);
  console.log("x.v:", x.v);
}

testDownload();


推荐阅读