Promise的then()方法

所有的Promise对象都有then()方法,这个方法接受两个参数。第一个参数叫做promise fullfilled是调用的函数,也叫做fulfillment处理器;与异步操作的任何相关数据都可以传递给这个函数。第二个参数是当promise被reject的时候调用的函数,也叫做rejection handler;与fullfillment handler类似,与rejection相关的任何异步操作数据都可以传递给这个函数。

以这种方式实现 then() 方法的任何对象都称为 thenable。 所有的promise都是 thenable,但并非所有 thenable 都是 promise。

 

then() 的两个参数都是可选的,因此您可以监听 fulfillment和rejection的任何组合。 例如,考虑这组then() 调用:

 const promise = fetch("books.json");

 // add a fulfillment and rejection handler
 promise.then(response => {
 	// fulfillment
 	console.log(response.status);
 }, reason => {
 	// rejection
 	console.error(reason.message);
 });

 // add another fulfillment handler
 promise.then(response => {
 	// fulfillment
 	console.log(response.statusText);
 });

 // add another rejection handler
 promise.then(null, reason => {
 	// rejection
 	console.error(reason.message);
 });

所有三个 then() 调用都基于相同的promise。 第一个调用分配了一个fullfillment和一个rejection处理程序。 第二个只分配一个fullfillment处理程序; 不会报告错误。 第三个只是分配一个rejection处理程序并且不报告成功。

fetch() 函数的一个怪癖是,只要它收到 HTTP 状态,甚至是 404 或 500,返回的 Promise 就会实现。只有当网络请求失败时,才会拒绝该 Promise
原因。 如果要确保状态在 200-299 范围内,可以检查 response.ok 属性,如下例所示:

 const promise = fetch("books.json");

 promise.then(response => {
	 if (response.ok) {
		console.log("Request succeeded.");
	 } else {
		console.error("Request failed.");
	 }
 });

总结:

1、理解什么叫做thenable对象

2、理解fullfillment和reject handler

 

版权声明:著作权归作者所有。

thumb_up 0 | star_outline 0 | textsms 0