developit / greenlet

🦎 Move an async function into its own thread.
https://npm.im/greenlet
4.67k stars 100 forks source link

Uncaught SyntaxError: Unexpected identifier in Chrome 69 #36

Closed Swizec closed 5 years ago

Swizec commented 5 years ago

Greenlet works great 👌

But it throws a worrying syntax error every time I call my greenlet function. I'm probably holding something wrong, but can't figure out what.

screenshot 2018-10-17 at 16 53 31

This goes away if I import but never call greenlet().

Here's how I'm using it:

import greenlet from 'greenlet';

function doTheThing(data) {
  greenlet(storeData(data));
}

async function storeData(data) {
  return BaseAPIManager.makeAPICall({
    endPoint: "...",
    data
  }).catch(err => save_data_to_localstorage(data))
}

Any idea what I could be doing wrong?

developit commented 5 years ago

Can you try in greenlet@0.1.2? This could be the data URL hash issue.

developit commented 5 years ago

If so this is the same cause as #32. Can fix by going back to Blobs.

Swizec commented 5 years ago

Still getting a syntax error. Except now it starts with blob:

screenshot 2018-10-18 at 13 15 05

Am I webpacking it wrong maybe?

Kanaye commented 5 years ago

Hi @Swizec. Greenlet only allows you to move pure functions off to a worker. In your example you aren't passing a function to greenlet but instead a promise. That 's also what is shown in your first screenshot within the data-uri [object Pro.

Also your function storeData isn't pure as it 's using things probably defined in other modules like BaseAPIManager or save_data_to_localstorage.

Also I don't think your usecase is really fits workers, it looks like you 're only sending data over the network and saving it somewhere when the request fails. Also the name save_data_to_localstorage sugests you are trying to access localStorage which isn't available to workers.

developit commented 5 years ago

Thanks @Kanaye! I missed that in his demo code.

It should be:

import greenlet from 'greenlet';

function doTheThing(data) {
  storeData(data)
}

const storeData = greenlet(async (data) => {
  return BaseAPIManager.makeAPICall({
    endPoint: "...",
    data
  }).catch(err => save_data_to_localstorage(data))
})

Just be aware, neither localStorage or BaseAPIManager would be available in the scope of the greenletted function.

FWIW if you're looking to offload a whole part of your Webpack bundle (all of BaseAPIManager), you will have a lot easier time with workerize-loader or Comlink-loader.

Swizec commented 5 years ago

Ah that makes sense. Thanks @developit and @Kanaye. I was trying to offload API calls for logs because they aren't important enough to run in the main thread.

But I don't think the optimization is worth the effort if I'd have to move over the API header machinery we've built up over the years.

Thanks for the help! Closing.

Today I learned a lot about workers :)