As suggested by @abadalyan, return a Promise from your getBase64Image
.
Also do not forget to check the status of the response with readyState
and status
and handle any errors using XMLHttpRequest.onerror
and XMLHttpRequest.ontimeout
using the reject
callback of the Promise.
You also have to check the FileReader
errors with FileReader.onerror
and FileReader.onabort
, or you could use the FileReader.loadend
callback instead of FileReader.load
to make sure the promise always resolves even when you get a read error.
Here is an example with error handling:
function getBase64Image(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onerror = e => reject(new Error('Reading error.', e));
reader.onabort = e => reject(new Error('Reading abort.', e));
reader.onload = () => resolve(reader.result);
} else {
reject(request.statusText);
}
};
xhr.onerror = e => reject(new Error('Network error.', e));
xhr.ontimeout = e => reject(new Error('Timeout error.', e));
xhr.send();
});
}
getBase64Image('https://cors-anywhere.herokuapp.com/https://loremflickr.com/100/100').then(image => {
console.log(image);
document.querySelector('#img1').src = image;
}).catch(e => console.error(e.message || e));
getBase64Image('wrong-url').then(image => {
console.log(image);
document.querySelector('#img2').src = image;
}).catch(e => console.error(e.message || e));
<img id="img1" src="" alt="No image yet">
<img id="img2" src="" alt="No image yet">