tom894
tom894

Reputation: 519

JavaScript Promise Not Returning Correct Value

Hey I've been learning promises and can't understand why a's value in undefined in the code below.

a = new Promise(function(resolve, reject) {
  setTimeout(function(){
    resolve(5);
  }, 1000);
});

console.log(a);

Any explanations would be really appreciated. Thanks.

Upvotes: 1

Views: 42

Answers (1)

brk
brk

Reputation: 50346

Here console.log will execute immediately and will show the value of a which has a promise object assigned to it. So it will log a as an object.You will like to log the value once the Promise is resolved. Try logging inside the then

a = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve(5);
  }, 1000);
});

a.then((data) => {
  console.log(data)
})

Upvotes: 3

Related Questions