0

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
) 

1 Answer 1

1

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);
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.