skip to Main Content

In this I have a doubt that res(p2) only gets resolved once p2 promise gets settled so how this mechanism works how do res know that p2 is pending.

function run(p2) {
  let p1 = new Promise((res, rej) => {
    console.log(p2)
    res(p2)
  })
  p1.then(val => console.log(val))
}
let p2 = new Promise((res, rej) => {
  setTimeout(() => {
    res('po')
  }, 6000)
})
run(p2)

2

Answers


  1. Here is a bit simplified example, showing how this works exactly:

    const base = new Promise((resolveFunc) => {
    
      resolveFunc(new Promise((innerResolveFunc) => {
        setTimeout(() => innerResolveFunc(), 2000);
      }))
    
    });
    
    base.then(() => console.log('resolved'))

    The base promise will be fulfilled, when the promise passed as an argument of resolveFunc is fulfilled. In this example, console.log will run after 2 seconds.

    Here is an explanation from MDN:

    The value parameter passed to resolveFunc can be another promise object, in which case the newly constructed promise’s state will be "locked in" to the promise passed (as part of the resolution promise).

    Login or Signup to reply.
  2. p1 is created and immediately resolved with the promise p2. Meaning that p1 transitions from the pending state to the fulfilled state, and its resolution value becomes p2.

    The .then() handler attached to p1 logs the value of p1, which is the p2 promise object itself.

    Promises are a way to work with asynchronous code in a more structured and manageable manner, allowing you to handle the results of asynchronous operations more elegantly and avoid callback hell. As a result you don’t need a timer in your code.

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