I get file list and want to make json array like
[
{"name":"IDCard001.jpg","base64":"data:image/jpeg;base64,/9j/4AA.."},
{"name":"IDCard002.jpg","base64":"data:image/jpeg;base64,/9j/4AA.."},
]
My code:
const getBase64 = (file: File) => {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = (error) => reject(error);
reader.readAsDataURL(file);
});
};
const handleFiles = (files: Array<File>) => {
const list = files.map(async (file) => {
return {
name: file.name,
base64: await getBase64(file),
};
});
}
I can not use list as simple array. How Do I?
CodePudding user response:
Its hard to be sure, but I think your issue is you are performing asyncronous operations within a map, so you need to ensure the promises resolve. I think this would solve your issue.
const handleFiles = async(files: Array<File>) => {
const list = await Promise.all(files.map(async (file) => {
return {
name: file.name,
base64: await getBase64(file),
};
}))
console.log(list)
}
CodePudding user response:
The map() method uses the return value of the function as it is See map() in MDN.
The variable list will contain a list of Promises instead of the intended object.
You should wrap the map with await Promise.all() See Promise.all()
in MDN and make the function async to have the objects array.
const handleFiles = async (files: Array<File>) => {
const list = await Promise.all(files.map(async (file) => {
return {
name: file.name,
base64: await getBase64(file),
};
}));
return list;
}
