Siubaak / sval

A javascript interpreter written in javascript
https://jsbin.com/kehahiqono/edit?js,console
MIT License
379 stars 50 forks source link

Why does async require '!' operator #93

Closed jdaly77 closed 1 year ago

jdaly77 commented 1 year ago

I noticed that when functions that are declared as 'async' are passed into the interpreter as a code string, the async always has to have the '!' in front of it. This does not seem to be explained anywhere. Can someone please explain why this is the case? Thanks!

milahu commented 1 year ago

maybe a hack for toplevel await ...

fwiw, im running async code with promises (resolve, reject)

https://github.com/milahu/search-aggregator-browser-extension/blob/main/src/pages/options/Options.tsx

import Sval from '@src/sval/dist'

    function search(searchQuery) {
      return new Promise((resolve, reject) => {
        const interpreter = new Sval({
          ecmaVer: 2019,
          sandBox: true,
        })
        interpreter.import({
          ...libraryFunctions,
          searchQuery,
          resolve,
          reject,
        })
        const fullSource = (
          source + "\n" +
          "search(searchQuery).then(resolve).catch(reject)" + "\n"
        )
        console.log(`calling backend ${name}`)
        try {
          // source will call resolve or reject
          interpreter.run(fullSource)
        }
        catch (error) {
          reject(new Error(error.message + "\n" + formatErrorContext(fullSource, error.pos)))
        }
      })
    }

notice the glue code

search(searchQuery).then(resolve).catch(reject)

the search code looks like

https://github.com/milahu/search-aggregator-browser-extension/tree/main/src/pages/options/search-backends

async function search(searchQuery) {
  // get hidden form values
  const response1 = await fetch(`${baseUrl}search.php`)
  if (response1.status == 429) {
    return "<div>error: rate limiting</div>"
  }
  // ...
  return results.outerHTML
}
Siubaak commented 1 year ago

https://developer.mozilla.org/en-US/docs/Glossary/IIFE