reactiverse / es4x

🚀 fast JavaScript 4 Eclipse Vert.x
https://reactiverse.io/es4x/
Apache License 2.0
882 stars 75 forks source link

How to make es4x wait for js execution to finish before deploying? #473

Closed fantasy0v0 closed 3 years ago

fantasy0v0 commented 3 years ago

I want to wait for some asynchronous operations to complete before deploying

pmlopes commented 3 years ago

@fantasy0v0 I've been experimenting with the code to define an "easy" to use, use case.

If we agree that the main verticle returns a "promise" to signal asynchronous start I can capture its result in 2 different options:

Option 1

The main script last action is of type "Promise". This works because the way "eval" works to load the script it always returns the last evaluated expression, for example:

// ... some code...
Promise.resolve('Verticle READY');

The last expression eval's to a Promise I can then delay the deployment to the result.

This however has the drawback that you need to carefully craft your script to have it evaluated at the end.

Option 2

A follow-up (and safer) alternative, which in fact, is still the same behavior as option 1 is to wrap the main script in a IFFE:

(function () {
  // some code...
  return new Promise((onResolve, onReject) => { ...}));
})();

So, this gives full control to tell when the verticle is ready or not.

What is your opinion on this solution?

pmlopes commented 3 years ago

I've shared this concept with: https://gitter.im/es4x/Lobby?at=5fd2577092aa1c4ef5d1403f so more people can comment.

pmlopes commented 3 years ago

I'm looking at the concept and it does not feel right. We can already declare a callback to be executed at undeploy time with:

process.on('undeploy', () => { ... });

Perhaps a more natural way to achive this would be:

process.on('deploy', () => { ... });

Then we ensure that we follow the same rules:

If a callback returns a Promise we wait for it. Otherwise, we just terminate. This makes the reasoning simpler as doesn't introduce any new behavior.

This alternative has the benefit that we can apply the same logic both to ESM and CJS.