9th Sep 2020, 9:43 AM
Sameer Crestha
Sameer Crestha - avatar
4 Antworten
+ 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
9th Sep 2020, 9:47 AM
Rei
Rei - avatar
+ 3
Try using setTimeout in a different way: setTimeout(() => { res("Task completed"); }, 3000);
9th Sep 2020, 9:47 AM
Rowsej
Rowsej - avatar
+ 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)});
9th Sep 2020, 2:16 PM
Calviղ
Calviղ - avatar
+ 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
9th Sep 2020, 9:50 AM
Abhay
Abhay - avatar