简体   繁体   中英

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?

by doing following adjustments:

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

promise1.then(result => {
  console.log(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.

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"}

@ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM