I'm trying to implement some functionalities when I end Up having an issue about execution order in typescript:
code:
new Promise((resolve) => {
setTimeout(()=>{
console.log("function11111");
resolve();
}
,3000);
})
.then(_=>{
setTimeout(()=>{
console.log("function22222");
}
,2000);
})
.then(_=>{
setTimeout(()=>{
console.log("function3333333");
}
,1000);
})
The OutPut:
function11111
function33333
function22222
My Questions are:
1)for function1111, if we replace this console.log('fucntion1111') by a function that takes some seconds, in this case, my code will fire resolve() before the function finish its execution, So how to ensure the wait for my function
2)In my code I'm doing then then, Why the execution doesn't respect my order ? I was thinking that promise is created for this purpose.
setTimeout
does not return a Promise. It returns an Integer instantly, so the.then()
is executed instantly. (You can make it return a Promise, though). In your "real world" code, make sure to return a Promise inside each.then()