Home > Software design >  How to control flow of async functions?
How to control flow of async functions?

Time:11-26

I have a chain of async functions, which need to be performed in order. Yet, if one of those functions fails or takes too long, it should be retriggered a certain amount of times.

So my questions is: What is the standard/elegant structure to have such a control flow with async functions? E.g.:

funcA()
    .then(resultA => funcB(resultA)
        .then(resultB => funcC(resultB)
            .then(...))

CodePudding user response:

You can do like this

function funcA() {
    return Promise.resolve('a');
}

function funcB(data) {
    return Promise.resolve(data   ' b');
}

function funcC(data) {
    return Promise.resolve(data   ' c');
}

async function controlFlowExample() {
  const resultA = await funcA();
  const resultB = await funcB(resultA);
  const resultC = await funcC(resultB);
  
  console.log(resultC);
}

controlFlowExample();

CodePudding user response:

You can use async-await to chain them neatly together:

const res_a = await funcA()
const res_b = await funcB(res_a)
const res_c = await funcC(res_b)

This is better than chaining .then since here it is easier to debug as you save more values.

Sidenote: if you do it this way, it is best to implement trycatch within your functions.

IMO it looks much neater too.

  • Related