I'm learning Promise. I wrote this simple code to practice the theoretical concepts learned. But it doesn't behave as expected. In my understanding the Promise.resolve
is in a resolve state, thereby the then()
is executed immediately and the object is passed as value
. The handler of the then()
return a Promise
because i want to seralize the asynchronous code. In the Promise the synchronous code is execuded instead the setTimeout
should be put in the Job Queue. Then, the synchronous execution code continue but the following then
doesn't exec because the calling Promise
is in a pending
state. Thus only when the callback of the setTimeout
run the Promise become in resolve
state and in the meanwhile pass the value Object. I would expect that the second console.log in the second then()
method to perform after 5 seconds but it isn't the case. The three console.log
print immediately.
Promise.resolve({id:"1",type:"person"})
.then((value) => new Promise((resolve,reject)=>{
console.log(value);
value.id="2";
setTimeout(resolve(value),5000);
}
))
.then((value) => new Promise((resolve,reject)=>{
console.log(value);
value.id="3";
setTimeout(resolve(value),5000);
}
))
.then((value)=>console.log(value));
This code works, but without to pass the object between the Promises:
Promise.resolve({id:"1",type:"person"})
.then((value) => new Promise((resolve,reject)=>{
console.log("1");
value.id="2";
setTimeout(resolve,5000);
}
))
.then(() => new Promise((resolve,reject)=>{
console.log("2");
setTimeout(resolve,5000);
}
))
.then(()=>console.log("3"));
Where am I wrong? Which puzzle piece am I missing?