There are different ways to chain asynchronous functions. In this case toDataUrl()
is an asynchronous function that uses callbacks. This cannot be combined with async/await
that way. That is, or use the await
and toDataUrl()
returns a Promise, or else toDataUrl()
returns a callback and chains the code inside the callback.
The two variants would be like this:
async getImageUrl(event, contentIndex: number) {
this.toDataUrl(event, (base64image) => {
console.log(base64image);
this.base64image = base64image;
// aqui podes escrever o resto do código
console.log("1");
});
}
toDataUrl(url, callback) {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
const reader = new FileReader();
reader.onloadend = () => {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
Using Promise:
async getImageUrl(event, contentIndex: number) {
const base64image = await this.toDataUrl(event);
console.log(base64image);
this.base64image = base64image;
// aqui podes escrever o resto do código
console.log("1");
}
toDataUrl(url, callback) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
const reader = new FileReader();
reader.onloadend = () => {
resolve(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
});
}
Find a variant of Promise and callback (without async/await
) here too: When to use Success: Function() and . done(Function()) in asynchronous requests?
You have to put async / await in all toDataUrl levels. In function itself, onload and Arrow functions below.
– Leonardo Getulio