javascriptnode.jsfontselectronfont-face

Does it make sense to create worker.js to handle promises?


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'])
    }
  )
}

Solution

  • 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.