为什么 .then() 处的值未定义链接到 Promise?

IT技术 javascript promise
2021-01-11 02:38:45

给定的

function doStuff(n /* `n` is expected to be a positive number */) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(n * 10)
    }, Math.floor(Math.random() * 1000))
  })
  .then(function(result) {
    if (result > 100) {
      console.log(result + " is greater than 100")
    } else {
      console.log(result + " is not greater than 100");
    }
  })
}

doStuff(9)
.then(function(data) {
  console.log(data) // `undefined`,  why?
})

为什么是data undefined.then()链接doStuff()调用?

6个回答

因为没有Promise或其他值return.then()链接到Promise构造函数。

请注意,.then()返回一个新Promise对象。

解决方案是对return一个值或其他函数调用,其中returnsa value 或Promisefrom .then()

function doStuff(n /* `n` is expected to be a positive number */) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(n * 10)
    }, Math.floor(Math.random() * 1000))
  })
  .then(function(result) {
    if (result > 100) {
      console.log(result + " is greater than 100")
    } else {
      console.log(result + " is not greater than 100");
    }
    // `return` `result` or other value here
    // to avoid `undefined` at chained `.then()`
    return result
  })
}

doStuff(9)
.then(function(data) {
  console.log("data is: " + data) // `data` is not `undefined`
});

@NiketPathak 赏金只是为了引起对问题或特定代码本身的关注,该问题已在不同问题中多次出现。如果在另一个答案中更好地描述了对预期结果的描述,则该问题将获得奖励积分。虽然调查本身是供后代参考的;没有其他原因。参见stackoverflow.com/help/self-answermeta.stackoverflow.com/q/291992
2021-03-28 02:38:45

当时面临的问题:

return 
(new Promise(..)) //the promise we want to return
.then(()=>undefined) // the promise were actually returning, which resolves to undefined

您可能已经注意到,然后返回一个新的Promise。这有一个很好的理由,它使Promise链接变得容易,例如:

getUser()//an asynchronous action
 .then(user=>login(user))//then if we get the user,promise to log in
 .then(token=>console.log("logged in,token is "+token) //then if we logged in, log it
 .catch(error=>"login failed");//catch all errors from above

但这也造成了我们面临的小陷阱。解决方案可能是返回原始Promise,而不是.then()自动返回新Promise因为它被解析为 undefined 因为 then 内部的函数没有明确返回某些东西:

//what were doing:
Promise.resolve(n*10)//the original promise resolves to n*10
.then(a=>undefined)//the then gets n*10 passed as a, but returns undefined
.then(b=>console.log(b));//b will be undefined  :0 

//what we want:
var promise=Promise.resolve(n*10);
promise.then(a=>undefined);//a is n*10, this resolves to undefined
promise.then(b=>console.log(b));//but this still logs n*10, as its the original promise  :) 

因此,如您所见,要返回原始Promise,我们只需将其存储在一个变量中,然后为其分配一个 .then 处理程序,并且仍然具有对原始Promise的引用,我们可以将其他处理程序分配给 ( 或 return )。

在行动:

function doStuff(n /* `n` is expected to be a number */) {

    //create a new promise and store it

    var promise=new Promise(function(resolve, reject) {
        setTimeout(function() {
           resolve(n * 10)
        },1000);
    });

    //add a then handler to this promise  

    promise.then(result=>console.log(result + " is "+result<100?"not":""+" greater than 100"));

    //return the original one

    return promise;

}

doStuff(9).then(function(data) {
  console.log(data) //not undefined, as original promise
})

doStuff 正在返回Promise. 但是,您的最后一个then函数没有返回任何值,因此data作为undefined.

在promise中,下一个then函数的参数值是前一个函数的返回值then

function doStuff(n /* `n` is expected to be a positive number */) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(n * 10)
    }, Math.floor(Math.random() * 1000))
  })
  .then(function(result) {
    if (result > 100) {
      console.log(result + " is greater than 100")
    } else {
      console.log(result + " is not greater than 100");
    }
    return result;
  })
}

doStuff(9)
.then(function(data) {
  console.log(data) // `90`
})

您不会从链接到 Promise 的 .then() 返回结果。您需要添加返回结果;到 .then()

因为您的数据值是 last 的返回值,所以.then()您的 last.then()没有有效的返回值。

因此,您可以在最后一个.then()函数中添加返回值