S
S
Sergey Sokolov2018-09-29 11:56:19
JavaScript
Sergey Sokolov, 2018-09-29 11:56:19

What is the correct way to write a conditional branch in the Promise chain?

In a chain of asynchronous operations, a condition is checked at some step. Further, a chain of asynchronous actions is optionally added before the final asynchronous step. I did something like this now, it works:

makeInitialPromise()
.then(r => {
  if (r > 0) { // Условие
    // надо дополнительные действия выполнить
    return makeAdditionalPromise(r)
    .then(r => makeAnotherAdditionalPromise());
  } else {
    // можно сразу переходить дальше
    return Promise.resolve(r);
  }
})
.then(r => makeFinalPromise());

Is it right to fence such nesting, or is it somehow still possible?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
profesor08, 2018-09-29
@profesor08

If you don’t like it, you can do it on async/await, it will turn out linearly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question