javascript - 从数组中获取 URL 列表并处理它们
问题描述
我正在尝试获取数组中的 URL 列表,然后将它们全部转换为 Base64。然而,我需要阻止函数运行,直到所有图像都被提取和处理,因为下一步需要输出。
预期过程应
let example = ["https://www.example.com/1.jpg", "https://www.example.com/2.jpg"];
转换为 Base64 编码数组。
//Contains the B64 encoded images
var observationImages = []
//List of Images to fetch and encode
var lookupPhotos = ['https://www.example.com/1.jpg', 'https://www.example.com/2.jpg'];
Promise.all(
lookupPhotos.map(url => {
fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
console.log('Converting to b64');
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
}))
.then(dataUrl => {observationImages.push(dataUrl)});
}
)
).then(data => {
console.log('Promises all resolved!');
console.log(observationImages);
});
我尝试过使用 Promises,但我不确定我是否完全理解它们是如何工作的,所以它不能按预期工作。
解决方案
此代码在我的浏览器中本地运行。
你能看到我改变了什么吗?
为了清楚起见,在 Promise 链之外声明了您的自定义 Promise 函数
将 blob 传递给读者。
在您的地图回调中放置一个返回,以便将承诺存储到数组中(否则您将得到一个空数组)。
resolve 和 reject 是您传递数据的方法。该数据通过承诺链传递。
您存储在数组中的链需要返回一个承诺。因此,将非承诺代码移至 Promise.all() 解决后。
最后添加了一个 .catch 。
// will contain the B64 encoded images let observationImages = []; //List of Images to fetch and encode let photosToLookUp = [ "https://www.gravatar.com/avatar/a70aa9d494bf438c8b56aced999e897f?s=48&d=identicon&r=PG", "https://www.gravatar.com/avatar/e0e123ac05632003d0ff22ec8ce3a554?s=32&d=identicon&r=PG" ]; const customPromise = blob => { return new Promise((resolve, reject) => { console.log("Converting to b64"); const reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = () => { resolve(reader.result); }; reader.onerror = err => { reject(err); }; }); }; Promise.all( photosToLookUp.map(url => { return fetch(url) .then(response => { return response.blob(); }) .then(blob => { return customPromise(blob); }); }) ) .then(arrayOfData => { console.log("Promises all resolved!"); arrayOfData.forEach(dataUrl => { observationImages.push(dataUrl); }); //there is no return value here because you've gotten all the info from the promise chain and are processing it. }) .catch(err => { console.log("error:", err); });
推荐阅读
- reactjs - ReactJs/NextJs 环境变量 - 不使用 getServerSideProps() 获取
- amazon-web-services - 如何使用 Terraform 禁用 AWS RDS 上的删除保护?
- php - 有没有合适的例子来集成 jobAdderApi
- sharepoint-online - 如何自动化将指定子文件夹添加到 SharePoint 中的文件夹的流程?
- sql-server - SQL Server 数据库触发器向导或对话框在哪里?
- html - html/css flex:使一个项目自身和容器按高度拉伸,其他在同一个容器中可滚动
- ocaml - 返回列表选项类型的 Ocaml 错误
- python - 在 tensorflow 2.2 中使用多个 GPU 和 tensorflow_hub
- anylogic - 模型开始运行后出现 3d 对象错误
- javascript - Angular Reactive Form Unit Testing:HTML 值和控件值不同步