skip to Main Content

I am studying javascript promises. The first code works fine, but the second code gives an error.

When catching errors, isn’t it sufficient for the reject function to be called? I don’t understand the difference between using and not using the return statement in this context.

I expect not only first code but also second code work fine

const f1 = () => {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("number1:complete")
    }, 2000)
  })
}

const f2 = (message) => {
  console.log(message)
  return new Promise((res, rej) => {
    setTimeout(() => {
      rej("number2:fail")
    }, 3000)
  })
}

//first code >> success
f1()
  .then(a => {
    return f2(a)
  })
  .catch(console.log)
  
//second code >> error
f1()
  .then(a => {
    f2(a)
  })
  .catch(console.log)

3

Answers


  1. In the second code snippet, you are missing a return statement

    then(a => { return f2(a) }) 
    
    Login or Signup to reply.
  2. reject does make the related promise rejected, but that’s it.

    In your second example since you’re not returning the promise it won’t affect the resulting promise.

    Your resulting promise from your .then is immediately resolved as it implicitly returns undefined.

    .catch only applies to the promise object, which was resolved. It doesn’t control anything about another promise that has been "detached" somewhere along the way.

    Login or Signup to reply.
  3. Without the return statement in this case, the Promise is never observed. By returning a Promise here:

    .then(a => {
      return f2(a)
    })
    

    that allows the chain of promise handlers (any additional calls to .then(), any call to .catch()) to observe the result of that Promise. Without returning it, the call to f2() just goes unobserved because there is no .then() or .catch() attached to it.


    A very common real-world example is calling .json() on the result of a fetch():

    fetch(someUrl)
      .then(result => {
        return result.json();
      })
      .then(data => {
        // do something with data
      });
    

    By returning the Promise from result.json() you can use that Promise in a follow-up .then() call in the overall chain. Without returning it, there’s nothing to follow-up on.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search