I've obviously got some missing knowledge when it comes to async-await
I expect the base64 for each image to be logged one after another in the same order as the batch list array and then I expect end to be logged.
I'm getting a load of undefined and end logged first! Eeek!
async function GetImages() {
async function blobToBase64(blob) {
const reader = new FileReader();
reader.onloadend = () => {
return reader.result;
};
reader.readAsDataURL(blob);
}
async function getBase64(url) {
const response = await fetch(url);
const blob = await response.blob();
const base64 = await blobToBase64(blob);
return base64
}
async function fetchBatchList() {
const batchList = [
"https://i.imgur.com/M0K21iS.jpg",
"https://i.imgur.com/uNbsNAd.jpg",
"https://i.imgur.com/QdqhGb9.jpg"
];
batchList.forEach(async url => {
const res = await getBase64(url)
console.log(res)
})
}
async function end() {
console.log('end')
}
await fetchBatchList();
await end();
}
GetImages();
Adding async to a function doesn't make it wait for the callback to be called.
You need to wrap your callback from FileReader in a promise to get the result.
You're also not awaiting anything in your fetchBatchList function. A good solution is to just map each item to a promise and then use Promise.all() to wait until all urls are finished.
async function GetImages() {
function blobToBase64(blob) {
// Create promise
return new Promise((resolve, reject) => {
const reader = new FileReader();
// Resolve value when done
reader.onloadend = () => {
resolve(reader.result);
};
// Reject if we have an error
reader.onerror = () => {
reject(reader.error);
}
reader.readAsDataURL(blob);
});
}
async function getBase64(url) {
const response = await fetch(url);
const blob = await response.blob();
const base64 = await blobToBase64(blob);
return base64
}
async function fetchBatchList() {
const batchList = [
"https://i.imgur.com/M0K21iS.jpg",
"https://i.imgur.com/uNbsNAd.jpg",
"https://i.imgur.com/QdqhGb9.jpg"
];
// Map each url to a promise
const list = batchList.map(url => {
return getBase64(url)
})
// Wait until all are done
const urls = await Promise.all(list);
console.log(urls);
return urls;
}
async function end() {
console.log('end')
}
await fetchBatchList();
await end();
}
GetImages();