greenoldman greenoldman - 4 months ago 16
Javascript Question

What is the idiom for optional asynchronous preprocessing in Javascript?

Let's say I have to do some computation, which for example consists of computing A (asynchronously, with callback) and then when A is computed, computing B (also async with callback).

The problem is A is optional, if there is no data for it, I should jump right at computing B.

Currently I use pretty ugly code with doubled B execution, something like this:

if (A)
computeA(A,() => computeB(B,() => console.log("done.")));
else
computeB(B,() => console.log("done."));


I am asking to avoid baking up some my solution, which would not be recognized by any JS developer :-) Is there some idiom for it?

Answer

This can be also done quite easily with promises:

if (A)
   p = A();
else
   p = Promise.resolve(defaultValue)

p.then(B).then(done)

assuming A and B both return promises. If they are traditional callback-acceptors, you have to promisify them.

Comments