Home > Net >  How i prevent calling nested then method?
How i prevent calling nested then method?

Time:01-25

Basically, I have login api and nested then function is there, my question is how I stop from calling as certain condition, pasting my code:

login(values.email, values.password)
  .then((res) => {
    if (res?.value?.data?.unverified) {
      console.log('>>> in', res, RESEND_VERIFICATION_EMAIL_DIALOG);
    } else getMe(true);
  })
  .then(() => ...)

So, if it comes in the above if I have to stop calling nested then and all code. Any help would be appreciated, thanks in advance :).

CodePudding user response:

One way to prevent calling nested then methods in JavaScript is to use async/await instead.

With async/await, you can use the await keyword to pause the execution of a function until a promise is resolved. The function containing the await keyword must be declared as async.

For example, consider the following code that uses nested then methods:

promise1()
.then(promise2)
.then(promise3)
.then(promise4)

This can be refactored to use async/await like this:

async function main() {
  const result1 = await promise1();
  const result2 = await promise2(result1);
  const result3 = await promise3(result2);
  const result4 = await promise4(result3);
}
main()

This way, each promise is awaited before calling the next one and you don't need to nest them.

Another way of preventing nested then method is by chaining the promise with Promise.all(), this way you can call multiple promises at the same time and wait for all of them to resolve at once.

Promise.all([promise1(), promise2(), promise3()])
.then(results => {
  // results is an array containing the resolved values from promise1, promise2, and promise3
})

It is important to note that using async/await or Promise.all() is a matter of preference and the best approach can vary depending on the specific use case.

CodePudding user response:

you'd better use .then, .catch

login(values.email, values.password)
.then((res) => {
    if (res?.value?.data?.unverified) {
      console.log('>>> in', res, RESEND_VERIFICATION_EMAIL_DIALOG);
    } else getMe(true);
}).catch(function(e) {
    console.log(e); // "oh, no!"
});

PS: I found a good resource about stopping the promise chain which I hope would help you

  • Related