小编典典

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

javascript

给定

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()电话吗?


阅读 431

收藏
2020-04-25

共1个答案

小编典典

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

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

解决方案是return使用returnvalue或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`

});
2020-04-25