Mateusz W
Mateusz W

Reputation: 66

Why there is undefined on fulfilled promise?

Can you explain me something?

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    if(true) {
      resolve('succes')
    } else {
      reject('failure')
    }
  }, 4000)
})

promise1.then(result => console.log(result))

Why after that i got 'succes' on console and something like this

Promise {<fulfilled>: undefined}

Why there is undefined if my promise returning 'succes' string value? This is beacause of setTimeout nesting? How could I fix this?

Upvotes: 0

Views: 10181

Answers (3)

Mechanic
Mechanic

Reputation: 5390

by doing following adjustments:

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    const stat = true;
    if(stat) {
      resolve('success')
    } else {
      reject('failure')
    }
  }, 4000)
})

promise1.then(
    result => {console.log('resolve', result); return result;},
    result => {console.log('reject', result); return result;}
)

you will have both log and promise return value on dev tools;

WHY?

undefined is the result of the implicit return value the callback (return;), when a function doesn't return anything explicitly, js engine will add implicit return statement to the end of function body.

Upvotes: 3

habib chabbi
habib chabbi

Reputation: 98

@ Mateusz W

1- The first log 'success' comes from the 'console.log(result)' that you have written.

2 -The second log 'Promise {: undefined}' is refering to the 'promise1.then(result => console.log(result))', because the 'then' function return itselelf a promise that resolves the result that you return inside it (in your case you return nothing inside then).

To be sure verify the following code :

promise1.then(result => console.log(result)).then(result1 => {})

you will obtain the following result

succes
undefined
Promise {<fulfilled>: undefined}

The undefined after the success is the one that you find in your 'Promise {: undefined}'

that correspond here to result1.

Do not confuse with this Promise {<fulfilled>: undefined} that you see here (result of my code) because this is referring to the second then that I chained to your then

In summary: you may were confused and thought that the Promise {<fulfilled>: undefined} that you saw in console is referring to you promise1 const. No it is not, it is the return of the then function.

Upvotes: 1

Adam Jenkins
Adam Jenkins

Reputation: 55792

To be fair, you aren't showing the code where you get

Promise {<fulfilled>: undefined}

But I imagine it could look something like this:

promise1.then(result => {
   console.log(result)
   console.log(promise1); // this line here
})

If you do this instead:

promise1.then(result => {
   console.log(result)
   console.log(promise1); 
   return result; // now this line here
})

Then you will see:

Promise {<fulfilled>: "succes"}

Upvotes: 0

Related Questions