reearth / quickjs-emscripten-sync

Provides a way to sync objects between browser and QuickJS
MIT License
64 stars 7 forks source link

evalCode async code problem #19

Closed NasaRocket closed 1 year ago

NasaRocket commented 1 year ago

const execute = async () => { try { const res = await someAsyncOperation(); console.log(res) } catch (e) { console.log(e) } }; execute(); i write this code to run (use arena.evalCode), but never return any res, if i should do something more? I have expose someAsyncOperation

rot1024 commented 1 year ago

Calling arena.executePendingJobs() is required to run pending jobs.

    const ctx = (await getQuickJS()).newContext();
    const arena = new Arena(ctx, { isMarshalable: true });

    arena.expose({
      console: {
        log: console.log,
      },
    });

    arena.evalCode(`
      const someAsyncOperation = async () => "hello";
      const execute = async () => {
        try {
          const res = await someAsyncOperation();
          console.log(res);
        } catch (e) {
          console.log(e);
        }
      };
      execute();
    `);

    arena.executePendingJobs();

    arena.dispose();
    ctx.dispose();
NasaRocket commented 1 year ago

Thanks you answer, but it doesn't work in my project. my project like this.

const ctx = (await getQuickJS()).newContext();
const arena = new Arena(ctx, { isMarshalable: true });
function someAsyncOperation() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('hello');
    }, 1000);
  });
}

arena.expose({
  console: {
    log: console.log,
  },
  setTimeout: (fn: () => void, time: number) => {
    setTimeout(fn, time)
  },
  someAsyncOperation,
});

arena.evalCode(`
      const execute = async () => {
        try {
          const res = await someAsyncOperation();
          // break in here, can't continue execute
          console.log(res);
        } catch (e) {
          console.log(e);
        }
      };
      execute();
 `);

arena.executePendingJobs();

arena.dispose();
ctx.dispose();
rot1024 commented 1 year ago

Must call excecutePendingJobs repeatedly. You need to implement the event loop on your own. For more information, please study the JavaScript working principle.

Also, this question has little to do with the functionality of quickjs-emscripten-sync itself, so please contact the quickjs-emscripten issue for more information.

NasaRocket commented 1 year ago

Thank you answer 🌟