解答 Promise 中的 "TypeError: Cannot read property 'then' of undefined" 问题

阅读时长 4 分钟读完

在使用 Promise 进行异步编程时,我们有时会遇到 "TypeError: Cannot read property 'then' of undefined" 的错误。这个错误通常发生在 Promise 链式调用中,下面我们来详细探讨这个问题。

问题分析

在 Promise 链式调用中,每个 then 方法都会返回一个新的 Promise 对象,因此我们可以通过链式调用来串联多个异步操作。但是,如果前一个 Promise 对象没有正确地返回一个新的 Promise 对象,那么后续的 then 方法就会无法调用,导致出现 "TypeError: Cannot read property 'then' of undefined" 的错误。

例如,下面的代码中,第一个 Promise 没有正确地返回一个新的 Promise 对象:

-- -------------------- ---- -------
-----------------
  -------- -- -
    ----------------- ----
  --
  -------- -- -
    ----------------- ----
  --
  -------- -- -
    ----------------- ----
  --
  -------------- -- -
    ---------------------
  ---
展开代码

在上面的代码中,第一个 then 方法没有返回一个新的 Promise 对象,导致后续的 then 方法无法调用,从而出现了 "TypeError: Cannot read property 'then' of undefined" 的错误。

解决方法

要解决这个问题,我们需要确保每个 then 方法都返回一个新的 Promise 对象。一种简单的方法是在每个 then 方法中返回一个新的 Promise 对象,例如:

-- -------------------- ---- -------
-----------------
  -------- -- -
    ----------------- ----
    ------ ------------------
  --
  -------- -- -
    ----------------- ----
    ------ ------------------
  --
  -------- -- -
    ----------------- ----
    ------ ------------------
  --
  -------------- -- -
    ---------------------
  ---
展开代码

在上面的代码中,每个 then 方法都返回一个新的 Promise 对象,从而确保了 Promise 链式调用的正确性。

另外,我们也可以使用 async/await 来简化 Promise 的链式调用,例如:

-- -------------------- ---- -------
----- -------- ------ -
  --- -
    ----- ------------------
    ----------------- ----
    ----- ------------------
    ----------------- ----
    ----- ------------------
    ----------------- ----
  - ----- ------- -
    ---------------------
  -
-

-------
展开代码

在上面的代码中,我们使用 async/await 来简化 Promise 的链式调用,从而避免了出现 "TypeError: Cannot read property 'then' of undefined" 的错误。

总结

在使用 Promise 进行异步编程时,我们需要确保每个 then 方法都返回一个新的 Promise 对象,以避免出现 "TypeError: Cannot read property 'then' of undefined" 的错误。另外,我们也可以使用 async/await 来简化 Promise 的链式调用。

来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/655abdebd2f5e1655d4f2843

纠错
反馈

纠错反馈