为什么我能';是否从Firebase存储URL开始创建JavaScript文件对象?
大家好,我不太喜欢Angular和JavaScript,我有以下问题 在一个角度分量中,我在一个对象数组上迭代。每个对象都包含一个表示Firebase存储服务上的图像的url属性 从这个URL开始,我想检索图像并创建一个全新的JavaScript文件对象 我正试图这样做:为什么我能';是否从Firebase存储URL开始创建JavaScript文件对象?,javascript,typescript,Javascript,Typescript,大家好,我不太喜欢Angular和JavaScript,我有以下问题 在一个角度分量中,我在一个对象数组上迭代。每个对象都包含一个表示Firebase存储服务上的图像的url属性 从这个URL开始,我想检索图像并创建一个全新的JavaScript文件对象 我正试图这样做: createFilesList(attachments: any[]) { console.log("createFilesList() START, attachments", attachm
createFilesList(attachments: any[]) {
console.log("createFilesList() START, attachments", attachments);
const attachmentsFiles = attachments.map(element => {
console.log("CURRENT IMAGE URL: ", element.url);
const urlToObject= async()=> {
console.log("BEFORE FATCH");
const response = await fetch(element.url);
// here image is url/location of image
const blob = await response.blob();
const file = new File([blob], 'image.jpg', {type: blob.type});
console.log("FILE: ", file);
}
});
console.log("attachmentsFiles: ", attachmentsFiles);
}
但它并没有像我所驱逐的那样起作用。基本上,它进入map()arrow函数,该函数被定义为在原始附件数组上迭代。它正确地打印了当前图像的URL,因此在控制台中,我正确地获得了firebase上图像的URL
然后,我尝试按照此示例从我的图像URL生成一个文件:
因此,我试图定义一个新的调用async()函数的urlToObject对象。问题在于,它从未进入异步函数体,因此这几行代码(以及该函数的以下所有行)从未被执行:
console.log("BEFORE FATCH");
我的代码有什么问题?我错过了什么?如何修复它?您正在创建一个函数
urlToObject
,但您没有调用它。你甚至不需要这个功能。您可以执行代码。但是代码包含异步函数调用。这意味着map
将创建承诺,您必须等待:
createFilesList(attachments: any[]) {
console.log("createFilesList() START, attachments", attachments);
Promise.all(attachments.map(async element => {
console.log("CURRENT IMAGE URL: ", element.url);
console.log("BEFORE FATCH");
const response = await fetch(element.url);
// here image is url/location of image
const blob = await response.blob();
const file = new File([blob], 'image.jpg', {type: blob.type});
console.log("FILE: ", file);
return file;
})).then(attachmentsFiles => {
console.log("attachmentsFiles: ", attachmentsFiles);
});
}
或者,您可以使createFilesList
async并等待所有响应:
async createFilesList(attachments: any[]) {
console.log("createFilesList() START, attachments", attachments);
const attachmentsFiles = await Promise.all(attachments.map(async element => {
console.log("CURRENT IMAGE URL: ", element.url);
console.log("BEFORE FATCH");
const response = await fetch(element.url);
// here image is url/location of image
const blob = await response.blob();
const file = new File([blob], 'image.jpg', { type: blob.type });
console.log("FILE: ", file);
return file;
}));
console.log("attachmentsFiles: ", attachmentsFiles);
}