greenoldman greenoldman - 3 months ago 7x
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.")));
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?


This can be also done quite easily with promises:

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


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