Promise 是 JavaScript 中处理异步操作的一种方式,它可以帮助我们更加优雅地处理异步操作的结果。在 Promise 中,.then() 和 .catch() 是两个常用的方法,它们分别用于处理 Promise 的成功和失败状态。
.then()
.then() 方法用于处理 Promise 的成功状态,它接受一个回调函数作为参数。当 Promise 成功时,该回调函数会被执行,并且会将 Promise 的成功结果作为参数传递给该函数。
示例代码:
-- -------------------- ---- ------- ----- ------- - --- ----------------- ------- -- - ------------- -- - ------------------- -- ------ --- --------------------- -- - -------------------- -- ------- --------- ---展开代码
在上面的代码中,我们创建了一个 Promise,它在 1 秒钟后会成功地返回一个字符串 'success'。当 Promise 成功时,.then() 方法中的回调函数会被执行,并且会将 'success' 作为参数传递给该函数。
.catch()
.catch() 方法用于处理 Promise 的失败状态,它接受一个回调函数作为参数。当 Promise 失败时,该回调函数会被执行,并且会将 Promise 的失败原因作为参数传递给该函数。
示例代码:
-- -------------------- ---- ------- ----- ------- - --- ----------------- ------- -- - ------------- -- - ---------- ------------------ -- ------ --- --------------------- -- - --------------------------- -- ------- --------- ---展开代码
在上面的代码中,我们创建了一个 Promise,它在 1 秒钟后会失败并返回一个 Error 对象。当 Promise 失败时,.catch() 方法中的回调函数会被执行,并且会将 Error 对象作为参数传递给该函数。
区别
.then() 和 .catch() 的区别在于它们处理的 Promise 状态不同。.then() 用于处理 Promise 的成功状态,而 .catch() 用于处理 Promise 的失败状态。如果 Promise 成功了,.catch() 方法不会被执行;如果 Promise 失败了,.then() 方法中的回调函数也不会被执行。
示例代码:
-- -------------------- ---- ------- ----- ------- - --- ----------------- ------- -- - ------------- -- - ------------------- -- ------ --- ------- -------------- -- - -------------------- -- ------- --------- ----- --- ----------------- -- -------------- -- - --------------------------- -- ------- --------- ---展开代码
在上面的代码中,我们创建了一个 Promise,它在 1 秒钟后会成功地返回一个字符串 'success'。在 .then() 方法中,我们通过 throw new Error('failure') 来模拟 Promise 失败的情况。当 Promise 失败时,.catch() 方法中的回调函数会被执行,并且会将 Error 对象作为参数传递给该函数。
指导意义
理解 .then() 和 .catch() 的区别对于我们正确地使用 Promise 非常重要。在实际开发中,我们通常会将 .then() 和 .catch() 方法链式调用起来,以便更好地处理 Promise 的状态。
示例代码:
-- -------------------- ---- ------- ----- ------- - --- ----------------- ------- -- - ------------- -- - ------------------- -- ------ --- ------- -------------- -- - -------------------- -- ------- --------- ------ ------ -- -------------- -- - -------------------- -- ------- ----- ----- --- ----------------- -- -------------- -- - --------------------------- -- ------- --------- ---展开代码
在上面的代码中,我们创建了一个 Promise,它在 1 秒钟后会成功地返回一个字符串 'success'。在第一个 .then() 方法中,我们返回了一个字符串 'foo',并将其作为参数传递给了第二个 .then() 方法。在第二个 .then() 方法中,我们通过 throw new Error('failure') 来模拟 Promise 失败的情况。当 Promise 失败时,.catch() 方法中的回调函数会被执行,并且会将 Error 对象作为参数传递给该函数。
因此,我们需要清楚地了解 .then() 和 .catch() 的区别,并且在实际开发中正确地使用它们,以便更好地处理 Promise 的状态。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d38dfaa941bf71346c5cd8