0

I came across following piece of code

const img = document.getElementById('id')
fetch(img.src)
.then(res => res.blob())
.then(blob => {
  const file = new File([blob], 'dot.png', blob)
  console.log(file)
})

at the following url

https://stackoverflow.com/questions/49925039/create-a-file-object-from-an-img-tag

What I am trying to do is declare a variable

var file = fetch(img.src)
           .then(res => res.blob())
           .then(blob => {
            const file = new File([blob], 'dot.png', blob)
            return file;
           });
 //then I want to use this file object here

However problem is my lack of understanding of fetch api, it seems main javascript would not wait for fetch to return the result into my file variable. Can some one please help me so that above piece of code will return a file object in my main javascript process so that I can use it elsewhere? Thanks Update: After seeing the responses, I did the following

async function CallAsyncFunction(img){
    var file = await fetch(img.src)
       .then(res => res.blob())
       .then(blob => {
        const file = new File([blob], 'dot.png', blob)
        return file;
       });
    return file;
 }
let file;
CallAsyncFunction(imgrc).then(resp=>{
  file=resp;
  //file here is correct object
});
console.log(file.name);//still no data in the main js code..what am I doing    wrong..:-(
user1063108
  • 662
  • 1
  • 10
  • 24
  • Your last code block is equal to: `async function CallAsyncFunction(img){ return fetch(img.src).then(res => res.blob()).then(blob => { const file = new File([blob], 'dot.png', blob) return file; })` – t.niese Aug 21 '19 at 18:51
  • The `console.log(file.name);` has the be where your `//file here is correct object` comment is. Currently `console.log(file.name);` is executed before the file is fetched. That's how asynchronous code works. Please read the linked duplicate carefully. – t.niese Aug 21 '19 at 18:52
  • Thanks for point to the other thread where this has been explained. AuxTaco, connexo – user1063108 Aug 21 '19 at 19:13

0 Answers0