How to get the result of asynchronous function?

Hello!
I have a file to send to the server, I only have the url to the file
In the vast great got code it works:
getFileFromUrl function(url=") {
 let xhr = new XMLHttpRequest();
 xhr.open('GET', url, true);
 xhr.responseType = 'blob';
 xhr.onload = (e) => {
 let reader = new FileReader();
reader.readAsDataURL(xhr.response);
 reader.onload = (e) => {
console.log(e.target.result)
};
};
xhr.send();
}

Question: how do I return from the function.target.result? I feel that it is necessary to async satanity, and how, knowledge is not enough.
Please can explanation, thank you!
April 7th 20 at 15:50
1 answer
April 7th 20 at 15:52
Solution
async function getFileFromUrl(url=") {
 let xhr = new XMLHttpRequest();
 xhr.open('GET', url, true);
 xhr.responseType = 'blob';
 let response = xhr.onload = (e) => {
 let reader = new FileReader();
reader.readAsDataURL(xhr.response);
 return reader.onload = (e) => {
 return e.target.result
};
};

 await xhr.send();

 return await response

}
Yes, it works, thank you!
How to understand where to write the await? - verner_Haag34 commented on April 7th 20 at 15:55
@Kaitlyn66, analog await setTimeout if you need to wait the completion of computation of a variable and a response from the server, write the await, but it's not likely await, try to remove the case to return.

let response = xhr.onload = (e) => { /* <==== Now e.target.result the result of this function, and we write a response and have it returned in the final result */
 let reader = new FileReader();
reader.readAsDataURL(xhr.response);
 /* Now the result of this function and we return it again r.target.result ====> */ return reader.onload = (e) => {
 /* Return r.target.result ====> */ return e.target.result
};
 };
- heloise_Kulas41 commented on April 7th 20 at 15:58
@Andreane.Mohr,
analog await setTimeout

No-no-no-no.

The dog's tail may not be equivalent to the paws of a cat. - Nestor_Zieme commented on April 7th 20 at 16:01
@Leila_Romaguera, this is how I see it, as I explain in such situations? Quote from learn.js:

The await keyword will force the JavaScript interpreter to wait until then, until the promis to the right of the await is not executed.
- heloise_Kulas41 commented on April 7th 20 at 16:04
@Andreane.Mohr, Yes, wait, stopping execution of the current thread. While you can use await only in async functions. Where it is a little similar to setTimeout? - Nestor_Zieme commented on April 7th 20 at 16:07
@Leila_Romaguera, he is waiting for the completion of the operation, and a timeout waiting for specified amount of time - heloise_Kulas41 commented on April 7th 20 at 16:10

Find more questions by tags JavaScript