skip to Main Content

I am building an electron app that allows the user to load font files from their local drive as FontFace instances or to FontFace. In some cases, there will be tens of thousands of files and therefore promises. When even a small portion of such a large number of promises are rejected for one reason or another, it hangs the application. In researching how to address this, I came across, among many other potential solutions, the idea of using workers. Because promises are asynchronous already, does it make sense to create a worker to merely handle the promises?

// renderer.js

myAPI.onFontListReady(jsonFontList => {

  const worker = new Worker('worker.js');

  jsonFontList.forEach(objFontData => {
    worker.postMessage({
      command: 'load and render',
      objFontData: objFontData
    })


// worker.js

addEventListener('message', message => {
  if (message.data.command === 'load and render')
    loadAndRender(message.data.objFontData)
})

function loadAndRender(objFontData) {
  const
    ff = new FontFace(`_${objFontData.newFileName}`, `url('${objFontData.newFilePath.replace(/\/g, '/')}')`)
  ff.load()
  .then(
    () => {
      document.fonts.add(ff)
      postMessage([objFontData])
    },
    error => {
      console.error('ERROR LOADING @FONT-FACE:', error)
      postMessage([objFontData, 'error'])
    }
  )
}

2

Answers


  1. Yes, using web workers for handling promises in your Electron app can be a good idea. Web workers run in the background and can perform tasks concurrently without affecting the main thread, which can help prevent the application from hanging when dealing with a large number of promises.
    Your implementation looks good for offloading the font loading and rendering to a web worker. This way, the main thread remains responsive while the worker handles the asynchronous tasks.

    However, keep in mind that web workers have some limitations, such as no direct access to the DOM. In your case, since you’re dealing with FontFace instances and rendering, it seems like you’re handling this appropriately in the worker.

    Login or Signup to reply.
  2. Promises are not asynchronous themselves.

    Promises are merely a notification system that is typically used with operations which are themselves asynchronous to get a structured notification of completion or error.

    So, a promise does not make anything asynchronous that wasn’t already asynchronous.

    There would generally be no need or benefit for moving an actual asynchronous operation to a thread since it’s already operating in the background in a non-blocking way. The main reason to move something to a thread is if it has blocking behavior.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search