0

I need to set the src attribute of an <img> tag using a fetch from a node server.

function fetchPicture(path) {
  fetch(path)
    .then(function(response) {
      return response.blob();
    })
    .then(function(myBlob) {
      return window.URL.CreateObjectURL(myBlob);
    });
}

However, when handling the promise in my .then(response), I get a file not found exception with pathToMyHTMLFile/undefined.

My path is of the kind http://localhost:8080/Images/fig3.png and the response is of status 200.

Any tips would be greatly appreciated!

Ramesh
  • 2,297
  • 2
  • 20
  • 42
Olivier L
  • 11
  • 1

1 Answers1

0

Your function doesn't return anything. You're returning the URL from the callback function, but that doesn't automatically bubble up. Instead, the function should return the entire fetch Promise, and then process it asynchronously when called, like fetchPicture('http://url.path.here').then(url => image.src = url) or similar.

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26
  • Ok I understand and applied your changes and @Emissary 's and now it works fine. If I understand correctly, you can not bubble up the return value from ```.then()```? – Olivier L Oct 10 '19 at 17:43
  • Correct. By definition, other code continues to run while asynchronous code is running "at the same time". That means the function continues on, and ends, before the fetch is complete, so there's no way to get the return value from the callback into the scope of the function before the function ends. That's why, when using promises, you typically return the promise chain and then just chain another handler onto it when you need to use its values; so the new handler will wait until the promises resolve before being called itself. – IceMetalPunk Oct 10 '19 at 17:45