developit / greenlet

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

Can't find variable: Promise #26

Closed Claire-Ke closed 6 years ago

Claire-Ke commented 6 years ago

[Vue warn]: Error in mounted hook: "ReferenceError: Can't find variable: Promise" I got this error when runing Safari 5.1.7,What should I do?

mkxml commented 6 years ago

This version of Safari doesn't support Promises. You can use a Promise polyfill.

rubencodes commented 6 years ago

So, the caveat here is just including a Promise polyfill in your code won't help. It has to go within the greenlet'd function, correct?

mkxml commented 6 years ago

@rubencodes Good point, code inside the function is executing in it's own context inside a Web Worker. So you would need Promise to be available in your code context too.

One possible workaround is passing a Promise polyfill down to your Web Worker code via simple dependency injection:

// Include greenlet and global Promise polyfill before this...

const resolveOnTruthy = greenlet((Promise, value) => {
  return new Promise((resolve, reject) => {
    value ? resolve() : reject('Sorry, not truthy...')
  })
})

resolveOnTruthy(Promise, 1).then(() => console.log('Resolved!'))

Note that the polyfill inside the worker is not needed if you are using synchronous code.

You do need the global/main polyfill anyways because greenlet use Promises internally.

rubencodes commented 6 years ago

Ah, so this would eliminate the need to duplicate the Promise implementation. Smart!

developit commented 6 years ago

2 other options:

greenlet(async function(value) {
  importScripts('https://unpkg.com/es6-promise@4.2.4/dist/es6-promise.auto.min.js')

  return await fetch('/foo')
})
greenlet(function(value) {
  // promise stand-in
  function callback(err, value) {setTimeout(()=>{callback[err?0:1](err || value)})}
  callback.then=r=>{callback[0]=r}
  callback.catch=r=>{callback[1]=r}

  callback(null, value ? true : false)
  return callback
})