kaytrance kaytrance - 1 year ago 80
Javascript Question

Synchronous promise-based methods?

I am trying to make so that some object's methods, that have a promise-based function calls inside worked synchronously.

Here, for example, we have a

object. It has some prototyped methods that calls promise-based functions. For testing purposes I have created a
function that returns a promise to output a message after certain time.

var Promise = require("promise");

var worker = function(param_a, param_b) {
this.param_a = param_a;
this.param_b = param_b;

worker.prototype.job1 = function() {
DummyPromise(1, 5000);

worker.prototype.job2 = function() {
DummyPromise(2, 3000);

worker.prototype.job3 = function() {
DummyPromise(3, 1000);

function DummyPromise(jobId, timeout) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(jobId, "finished.");
}, timeout);

var w = new worker("aa", "bb");

If I run the code as is it will output something like:

3 finished.
2 finished.
1 finished.

..because all 3 methods are executed immediately, and the output depends on timeout.

Now the idea is to rewrite
functions so that they become synchronous and in result I get:

1 finished
2 finished
3 finished

Now the solution to use something like
is not a variant, because I do not have to run just 3 methods one by one - instead I will eventually have some complicated logic in the program that requires to run and rerun different jobs and I need to make sure that each job is executed synchronously to avoid callback hell and spaghetti code in final program.

Eventual program environment would be node.js, if it matters. No Babel.

Note Maybe a co or coroutines could be a solution? Looks very promising.

Answer Source

Well, the only good solution I have managed to find was to use async/await module from here.

It now works just ideal.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download