Problems with returning values using NodeJS Promise then

encountered the following phenomena when self-learning Promise:

var promise1 = Promise.resolve([1, 2, 3]);

function promise2() { 
  promise1.then(function(value) {
      return Promise.resolve(value);
  // expected output: Array [1, 2, 3]
  })
}

promise2().then(function(value){
    console.log(value);
})

the error is as follows:

promise2().then(function(value){
          ^

TypeError: Cannot read property "then" of undefined

normal return after adding return to modify

var promise1 = Promise.resolve([1, 2, 3]);

function promise2() { 
  return promise1.then(function(value) {
      return Promise.resolve(value);
  // expected output: Array [1, 2, 3]
  })
}

promise2().then(function(value){
    console.log(value);
})

what is the principle behind these two?

May.22,2021

  1. without return promise2 returns undefined of course there is no then method;
  2. if you want to ask clearly that return Promise.resolve (value) is a promise object but gets a value in then ;

is actually specified by promise/A+ specification , and nodejs implements Promise ;

according to this specification.

something similar is as follows:

var obj = {
    then: function(ok,no){
        ok('ok')
    }
}
Promise.resolve(obj).then(function(v){
    console.log(v);  // ok
})
To sum up, if the returned value is the function or object and there is a then' method, the then' will be used as then of the promise object, and
if there is still a then', continue to tune.


(() = > {}) () .
undefined anything wrong.
you write return and return a Promise object, and then you can continue.

clipboard.png

clipboard.png

Menu