+ 1
How to make this promise work?
4 Respostas
+ 4
something like this, only call res when you think the function should return. if it should return after waiting in set timeout, then call it when the timeout done
setTimeout(()=>{res("Task Complete")},3000);
same applied with rej/reject, call it only when the function cannot continue. maybe in case of Exception or something
+ 3
Try using setTimeout in a different way:
setTimeout(() => {
res("Task completed");
}, 3000);
+ 2
Sameer Crestha For your example of using Promise with setTimeout, you only need to call res("message to show"); in the callback of setTimeout for successfully execution, if errors, call ref("error") function instead.
function waitsthreesec(){
return new Promise((res,rej)=>{
let isDone;
setTimeout(()=>{
let err;
// processing data, set err = true if error encountered
if(err) rej("Error"); // this would pass the arg to and run .catch function
else res("timer message"); // this would pass the arg to and run .then function
},3000);//a task that will take 3 second to complete
});
}
waitsthreesec().then(msg=>{console.log(msg)}).catch(err=>{console.log(err)});
+ 1
It has do with how events work in js ,they are asynchronously executed and that is what is happening inside the promise ,your setTimeout executes after 3 seconds but if and else are executed immediately ,and so task is rejected ,all you need to do is put those if else inside setTimeout