skip to Main Content

How could this be done without repeating "DoTheNextThing();"?

    if (dosomething)
        DoSomething(function () {
            DoTheNextThing();
        })
    else
        DoTheNextThing();

I haven’t tried anything else because I can’t think of anything else to try.

2

Answers


  1. It’s not pretty, but you can use a function that just calls its argument, and assign it conditionally to a variable.

    const f = dosomething ? DoSomething : cb => cb();
    f(DoTheNextThing);
    
    Login or Signup to reply.
  2. Instead of DoSomething, choose a function that does nothing and then calls the callback:

    function DoNothing(callback) { callback(); }
    
    (dosomething ? DoSomething : DoNothing)(DoTheNextThing);
    

    However, assuming DoSomething is an asynchronous function, you really should rewrite it to return a promise, then use async/await for much cleaner code:

    if (dosomething)
        await DoSomething();
    DoTheNextThing();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search