0

I have many functions, each of them will return an ok status, and I want to call them one by one, and stop calling the next one if the previous one returning falsy ok status.

function func1() {}
function func2() {}
function func3() {}

const ok1 = func1();
if (ok1) {
  const ok2 = func2();
  if (ok2) {
    func3();
  }
}

but in this code style, I get too many nested curly braces, how do I make it better?

Littlee
  • 3,791
  • 6
  • 29
  • 61

2 Answers2

1

As shrys mentions you can chain using && if you're expecting truthful values:

func1() && func2() && func3() && ...;

If you have a lot of arguments where the single-line style would be too messy:

if (!func1(...)) return;
if (!func2(...)) return;
if (!func3(...)) return;

Where those are inside of a function so you can break out with return.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

If you want to use your existing functions as-is then the two techniques described in tadman's answer are good. However there is a cleaner way to handle this but it needs you to modify your existing functions: just throw an error.

function func1() {if (fail) throw new Error('Failed')}
function func2() {if (fail) throw new Error('Failed')}
function func3() {if (fail) throw new Error('Failed')}

try {
    func1();     // This part becomes much cleaner
    func2();
    func3();
}
catch (e) {
    // Error handling is localized to this block of code
    console.log(e.message);
}

Ideally for situations like this I personally like to return a custom error so that I know it is caused by my own code and I can handle them properly (mostly just ignore them) and then re-throw other error types. But weather you do this or not is up to you:

class FunctionFailureError extends Error {
    constructor(message) {
        super(message);
        this.code = 'FUNC_FAIL_ERROR';
    }
}

function func1() {if (fail) throw new FunctionFailureError('Failed')}
function func2() {if (fail) throw new FunctionFailureError('Failed')}
function func3() {if (fail) throw new FunctionFailureError('Failed')}

try {
    func1();
    func2();
    func3();
}
catch (e) {
    if (e.code === 'FUNC_FAIL_ERROR') {
        console.log(e.message);
    }
    else {
        throw e;
    }
}
slebetman
  • 109,858
  • 19
  • 140
  • 171