kaytrance kaytrance - 3 months ago 13
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

worker
object. It has some prototyped methods that calls promise-based functions. For testing purposes I have created a
DummyPromise
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");
w.job1();
w.job2();
w.job3();


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
job1
,
job2
and
job3
functions so that they become synchronous and in result I get:

1 finished
2 finished
3 finished


Now the solution to use something like
async.mapSeries
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

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

It now works just ideal.

Comments