Qn. Create a JavaScript Promise that, after a delay of 2 seconds, either resolves with the message "Hello World" or rejects with the error message "Error occurred". The outcome (resolve or reject) should be determined by a random condition, ensuring a 50/50 chance of either occurring each time the code runs.
Solution Code has been given in description. However, I have tried to pass the random value based on which the resolution/ rejection takes place, but that value is displayed as undefined in then and catch parts of the code.
const Promises = new Promise((resolve, reject) =>
{
let ch = Math. Random()>0.5;
setTimeout(() =>
{
if(ch)
resolve("Hello World",ch);
else
reject("Error Occurred!!!",ch);
},2000);
});
Promises.then((msg,ch) =>
{
console.log(msg);
console.log(ch);
}).catch((msg,ch)=>
{
console.log(msg);
console.log(ch);
});
Output 1
Hello World
undefined
Output 2
Error Occurred !!!
undefined
Promise return single value(can be anything like string, array or objects etc) just like normal function.