I am trying to rewrite a synchronous junction to work with promises, and am a bit stuck with it. I have a function that call different routines A
, B
, and C
, depending on arguments and results:
const worker = (v, r, ok, er)=>{
if(v > 10) {
ok(r)
} else {
er(r)
}
};
const A = v=>{let r = null; worker(v, 'a', _r=>r=_r, ()=>{});return r};
const B = v=>{let r = null; worker(v, 'b', _r=>r=_r, ()=>{});return r};
const C = v=>{let r = null; worker(v, 'c', _r=>r=_r, ()=>{});return r};
const mainSync = (obj)=>{
let result = null;
if(obj.a) {
result = A(obj.a);
}
if (!result && obj.b) {
result = B(obj.b);
}
if (!result && obj.c) {
result = C(obj.c);
}
return result;
}
which works fine https://repl.it/JcjE/0 with synchronous A
, B
, and C
:
mainSync({a:4}) === null;
mainSync({a:4, b:14}) === 'b';
mainSync({a:14, b:14}) === 'a';
mainSync({b:4, c:14}) === 'c';
// etc
Now A
, B
, and C
become Promises:
const worker = (v, r, ok, er)=>{
if(v > 10) {
ok(r)
} else {
er(r)
}
};
const A = v=>new Promise((ok, er)=>worker(v, 'a', ok, er));
const B = v=>new Promise((ok, er)=>worker(v, 'b', ok, er));
const C = v=>new Promise((ok, er)=>worker(v, 'c', ok, er));
and I am not quite sure how to handle it:
const mainAsync = (obj)=>{
// what todo here?
}
I am happy with mainAsync to return Promise itself, like
mainAsync({a:4}).then(r=>r === null);
mainAsync({a:4, b:14}).then(r=>r === 'b');
mainAsync({a:14, b:14}).then(r=>r === 'a');
mainAsync({b:4, c:14}).then(r=>r === 'c');
The problem is that call to B
depends on result of A
, and call to C
depends on results of both A
and B
, and no async/await
available yet.
I have tried my naive approach https://repl.it/Jcjw/0 but it is terrible and doesn't quite work on real life scale.
PS: I am looking for vanilla javascript if possible, and am aware about similar questions like
- Sequential call of promises,
- How to execute promises sequentially, passing the parameters from an array?,
etc, but couldn't figure out how to apply them to my case.