Promise 是一种用于处理异步操作的 JavaScript 对象,让我们可以更优雅和有效地组织和处理代码。作为 Promise 最核心的方法之一,then()
是 Promise 实例方法中最常用的。然而,虽然 then()
被广泛使用,但它到底是如何工作的呢?
then()
方法的基本语法
then()
方法是 Promise 对象实例方法的核心之一,使用它可以处理 Promise 返回的结果或错误信息。then()
最基本的语法如下:
promise.then(onFulfilled, onRejected)
其中,then()
方法接收两个参数:当 Promise 处理成功的时候,会调用 onFulfilled
回调函数;当 Promise 处理失败的时候,会调用 onRejected
的回调函数。这两个回调函数都是可选的,它们分别代表处理 Promise 成功和失败时所需要执行的代码。
then()
方法的工作原理
当 Promise 对象的状态发生改变时(状态变成 resolved
或者是 rejected
),就会调用相应的 then()
方法。
then()
方法处理 Promise 成功的返回值
当 Promise 状态被改变为 resolved
时,即 Promise 成功的时候,then()
方法将会执行 onFulfilled
回调函数,同时把 Promise 返回值作为参数传递给该回调函数:
let promise = new Promise(function(resolve, reject) { resolve("Promise success") }) promise.then(function(value) { console.log(value) // Promise success })
在这个例子中,Promise 返回了一个字符串 "Promise success"
。然后,then()
方法中的 function(value)
就会接收到这个字符串参数,并输出到浏览器控制台中。
then()
方法处理 Promise 错误
当 Promise 状态被改变为 rejected
时,即 Promise 失败的时候,then()
方法将会执行 onRejected
回调函数,同时把 Promise 错误信息作为参数传递给该回调函数:
let promise = new Promise(function(resolve, reject) { reject(new Error("Promise failed")) }) promise.then(null, function(error) { console.log(error.message) // Promise failed })
在这个例子中,Promise 返回了一个 Error
对象,它的错误信息是 "Promise failed"
。然后,then()
方法中的 function(error)
就会接收到这个错误参数,并将错误信息输出到浏览器控制台中。
then()
方法的链式调用
then()
方法可以被链式调用,这也是 Promise 最有价值的部分之一。链式调用 then()
方法可以根据操作结果进行后续操作,并且极大地减少了回调地狱的情况。
链式调用成功回调
-- -------------------- ---- ------- --- ------- - --- ------------------------- ------- - ---------------- --------- -- ----------------------------- - ------ -------------------- ------------------------ - ------------------- -- ------- ------- --
在这个例子中,第一个 then()
的回调函数中,我们将 result
转化为全大写字母,然后通过返回 result.toUpperCase()
将修改后的结果传递给链式调用下一个 then()
的回调函数。
链式调用失败回调
-- -------------------- ---- ------- --- ------- - --- ------------------------- ------- - ---------- -------------- --------- -- ----------------------------- - ------ -------------------- ------------------------ - ------------------- ------------------------ - -------------------------- -- ------- ------ --
在这个例子中,因为 Promise 处理失败了,所以第一个 then()
的回调函数永远不会执行,直接跳转到 catch()
方法中处理 Promise 错误信息。
总结
通过本文的学习,我们了解了 then()
方法的基本语法和工作原理,并通过示例代码实现链式调用。最后,这些知识和技术全都掌握了,再没有 then()
会让我们感到困惑和不安,现在你可以用 Promise 编写更加优雅和高效的异步 JavaScript 代码了。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/647d7487968c7c53b083dfc4