为什么 .then() 处的值未定义链接到 Promise? [英] Why is value undefined at .then() chained to Promise?

查看:12
本文介绍了为什么 .then() 处的值未定义链接到 Promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定

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() 调用?

Why is data undefined at .then() chained to doStuff() call?

推荐答案

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

Because no Promise or other value is returned from .then() chained to Promise constructor.

注意 .then() 返回一个新的 Promise 对象.

Note that .then() returns a new Promise object.

解决方案是从.then()<return一个值或其他函数调用returnsa value或Promise/代码>.

The solution is to return a value or other function call which returns a value or Promise from .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`
});

这篇关于为什么 .then() 处的值未定义链接到 Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆