🏠 back to Observable

Problem with awaiting a FileAttachment

I’ve got a notebook that does something like the following:

  create canvas;
  draw image to canvas;

The image is contained in a File Attachment and is loaded in a separate cell using this common idiom:

img_url = FileAttachment('image.png').url()

The odd thing is that sometimes the image appears and sometimes it doesn’t. As I understand it, the FileAttachment returns a Promise that other cells should wait for when they depend explicitly on that value. It looks to me like that might not be happening in this case, though perhaps there’s another issue I’m not aware of.

Here’s a simplified version of the notebook exhibiting the problem:

If the image does appear when you first open it, try closing and reopening a few times.

Waiting for the image’s URL and the image’s contents are two different operations. Sometimes your drawImage is failing because the image has not yet loaded. Try this:

img = FileAttachment("…").image()

Hmm… I don’t know why FileAttachment("…").image() and FileAttachment("…").url() would behave differently with respect to Promises. Having said that, I do have a work around in my actual working notebook that uses FileAttachment("…").image() to attach the image to a div.


They’re different because image() only resolves after the image is loaded, whereas url() resolves when the URL is available (without loading the file).

I encounter a problem when I use await from a function.

SyntaxError: Unexpected token
function test3 {
return html<button type="button" class="btn btn-default" id="first"><img src="${await FileAttachment( "first.png" ).url()}"></button>;

Have a look to https://observablehq.com/@pbrockmann/animation-controls

Hi, just noticed you are using await inside a normal function, you need to use async function animationControls(){ … to use await… its not related to observable.

async function test3() {
return html `<button type="button" class="btn btn-default" id="first"><img src="${await FileAttachment( "first.png" ).url()}"></button>` ;
1 Like

Ok (gloups). Thanks !!

1 Like