Can't load font (even though using loadFontAsync successfully...)

I can’t seem to write out characters to the text object I am a creating. Curious as to where I’m going wrong. I can see in the console that loadFonts() is being called and are being loaded, but I still get:

Figma_app.675c000d3a9960c3788bc94e9091401b.min.js.br:39 Error: in set_characters: Cannot write to node with unloaded font “Roboto Regular”. Please call Figma.loadFontAsync({ family: “Roboto”, style: “Regular” }) and await the returned promise first.

Unsure what more I need to do.

let node = figma.currentPage;
const nodes = node.findAll(node => node.type === "RECTANGLE");

const fonts = [
  { family: 'Roboto', style: 'Regular' },
  { family: 'Roboto', style: 'Bold' },
];

function loadFonts() {
  fonts.forEach(function (font) {
    figma.loadFontAsync(font);
    console.log('loaded');
  }
}

loadFonts();

for (let i = 0; i < nodes.length; i++)
{
  for (const paint of nodes[i].fills) {
    // only get the images, not the other rectangles
    if (paint.type === 'IMAGE' && nodes[i].name === 'SCREENSHOT') {

      // create a frame and position it near the image
      const frame = figma.createFrame()
      figma.currentPage.appendChild(frame)
      frame.x = nodes[i].x -150;
      frame.y = nodes[i].y - 100;
      frame.cornerRadius = 20;
      frame.fills = [{ type: 'SOLID', color: {r: .9, g: 0.4, b: 0.1} }];
      frame.layoutMode = "HORIZONTAL";

      // create the text and append it to the frame
      const screenshotText = figma.createText();
      frame.appendChild(screenshotText);
      screenshotText.x = frame.x + 50;
      screenshotText.y = frame.y + 50;
      screenshotText.characters = "screenshot";
    }
  }
}

figma.closePlugin();

The key words in the error message you see are “await the returned promise first”. loadFontAsync is an async method as the name suggests. You need to synchronize your code, the simplest way to do that is to wrap everything into an async function and use await to wait for the async functions to finish.

Let me try it out!

Hi!

The documentation about loading the fonts could be much better IMO. Maybe there could be some easy code snippets.

I got the fonts working like this:

// Function for loading all the needed fonts
const loadFonts = async () => {

  await figma.loadFontAsync({ family: "Work Sans", style: "Regular" })
  await figma.loadFontAsync({ family: "Work Sans", style: "Medium" })
  await figma.loadFontAsync({ family: "Work Sans", style: "Bold" })

  console.log("Awaiting the fonts.")

}

// Load the fonts by running the function
loadFonts().then(() => {

  // Make them useful
  doSomethingElseWithThem()
  console.log("Fonts fetched and ready to go!")

})

Maybe this helps someone!

4 Likes

Super helpful. Thanks!!

2 Likes