Reputation: 622
if I store the value of the promise return by a function in a variable and then print it then it shows Promise { pending }. Why ? Because till 3 seconds promise will definitely resolved.
let move = false;
function my() {
return new Promise(
(resolve, reject) => {
if (move === true)
return resolve("resolved")
else
return reject(new Error("Rejected"));
})
}
let obj = my().then((result) => {
console.log("result", result);
})
.catch((err)=>{
console.log("my error");
});
//it prints promise{ <pending> }
setTimeout(()=>{
console.log("time", obj)},3000
)
Upvotes: 0
Views: 60
Reputation: 552
The promise should wrap the setTimeout
function and resolve after 3 seconds is over.
let move = false;
function my() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (move) {
resolve('resolved');
} else {
reject(new Error('Rejected'));
}
}, 3000);
});
}
my()
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err.message);
});
Upvotes: 1