最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

为什么在循环内执行Promise时对象数组会为空

运维笔记admin10浏览0评论

为什么在循环内执行Promise时对象数组会为空

为什么在循环内执行Promise时对象数组会为空

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

下面的代码有什么问题?

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

您可以生成一个承诺列表,然后执行Promise.all以获取结果数组。这可以用来填充x.v数组。

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);
  console.log(resultList);
  x.v = x.v.concat(resultList);
  console.log("x.v:", x.v);
}

testDownload();
发布评论

评论列表(0)

  1. 暂无评论