0

What will be the output of the following JavaScript Promise code and how does it work?

author
kallyani
easy
3
65
Promise.resolve(1).then(val => {

console.log(val);

return val + 1;

}).then(val => {

console.log(val);

});
Answer
1
2

Explanation

  • Promise.resolve(1) creates a promise that is already resolved with the value 1.
  • The first .then() receives val = 1.
    • It logs 1
    • Returns val + 1, which is 2
  • When a value is returned from .then(), it is automatically wrapped in a resolved promise.
  • The second .then() receives the returned value 2.
    • It logs 2

Key Points

  • Each .then() receives the value returned from the previous .then()
  • Returning a value from .then() passes it to the next .then()
  • Promises allow value chaining

Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0
    What will be the output of the following JavaScript Promise code and how does it work? | promises | EBAT