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
Here is a bit simplified example, showing how this works exactly:
The
base
promise will be fulfilled, when the promise passed as an argument ofresolveFunc
is fulfilled. In this example,console.log
will run after 2 seconds.Here is an explanation from MDN:
p1
is created and immediately resolved with the promisep2
. 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 thep2
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.