node.js - 为什么在循环内执行 Promise 时对象数组变为空
问题描述
下面的代码将返回 [{}]
下面的代码有什么问题?
fileId.forEach((element) => {
getFileFromCloud(element)
.then((result) => {
console.log(result);
x.v.push({ dataUrl: result });
})
.catch((err) => {
console.log(err.message);
});
});
解决方案
您可以生成一个 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();
推荐阅读
- amazon-web-services - 如何使用带有 ubuntu 映像的 docker 卷来访问从 AWS S3 下载的文件?
- android - 是否可以运行 android 模拟器,获取其状态的图像文件,并使用它从无头 linux 服务器模拟鼠标功能?
- node.js - 发布 shell 脚本并完成构建
- java - 如何从 java 中的命令行参数或 stdin 重定向中读取?
- asp.net-core - 使用 FromForm 时将 DateTime 转换为 UTC
- linux - 如何检查给定参数是否是符号链接/软链接?在 bash
- c - 修改订单不是总订单是什么意思?
- ansible - 条件 set_fact 不评估
- javascript - 如何使用 Selenium 在 JavaScript 网站上查找元素?
- php - Wordpress 页脚菜单