BobHanson / java2script

Java2Script provides an Eclipse Java to JavaScript transpiler, with a nearly complete implementation of the Java Virtual Machine with AWT and Swing in JavaScript, with simple, automated parallel creation of both class files and js files. To date, over 600 applets have been converted.
https://chemapps.stolaf.edu/swingjs/examples.htm
Other
24 stars 11 forks source link

[About async in ecmascript] Is it possible to implement Thread.sleep() ? #228

Closed Lanius-collaris closed 8 months ago

Lanius-collaris commented 2 years ago

I saw a example on mdn.

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved')
    }, 2000)
  })
}
async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds()
  console.log(result)
  // expected output: "resolved"
}
asyncCall()

babel try it out output:

"use strict"
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
​function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved')
    }, 2000)
  })
}
function asyncCall() {
  return _asyncCall.apply(this, arguments)
}
function _asyncCall() {
  _asyncCall = _asyncToGenerator(function* () {
    console.log('calling')
    const result = yield resolveAfter2Seconds()
    console.log(result); // expected output: "resolved"
  })
  return _asyncCall.apply(this, arguments)
}
asyncCall()
BobHanson commented 2 years ago

Sorry for not spotting this. It is not possible to implement Thread.sleep.

BobHanson commented 2 years ago

But in every case we have seen there are simple alternatives. See the javajs.async.SwingJSUtil$StateMachine class and many examples. There is a discussion of how to use equivalents to java.lang.Thread in doc/Differences.txt as well.

These methods have been used many times in multiple projects.