【问题标题】:Why is value undefined at .then() chained to Promise?为什么 .then() 的值未定义链接到 Promise?
【发布时间】:2017-06-08 15:15:12
【问题描述】:

给定

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

【问题讨论】:

标签: javascript promise


【解决方案1】:

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

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

解决方案是return 一个值或returns 一个值的其他函数调用或来自.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");
    }
    // `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
【解决方案2】:

面临的问题:

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

您可能已经注意到,then 返回一个新的承诺。这是有充分理由的,它使 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

但这也造成了我们面临的小陷阱。解决方案可能是返回 original promise 而不是 .then() 自动返回的 new promise 因为这被解析为未定义为函数里面 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  :) 

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

在行动:

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

【讨论】:

    【解决方案3】:

    doStuff 正在返回 Promise。但是,您的最后一个 then 函数没有返回任何值,因此 dataundefined 的形式出现。

    在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`
    })

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

          您必须从链接到 Promise 的 .then() 返回结果。 在你的情况下,只需添加

          return result;
          

          到第一个.then()

          【讨论】:

            猜你喜欢
            • 2017-07-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多