关于promise的那些事

160 阅读5分钟
  1. 对象的状态不受外界影响。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。这也是Promise这个名字的由来,它的英语意思就是“承诺”,表示其他手段无法改变。

  2. 一旦状态改变,就不会再变,任何时候都可以得到这个结果。Promise对象的状态改变,只有两种可能:从pending变为fulfilled和从pending变为rejected。

  3. Promise 新建后就会立即执行。

    let promise = new Promise(function(resolve, reject) {
      console.log('Promise');
      resolve();
    });
    
    promise.then(function() {
      console.log('resolved.');
    });
    
    console.log('Hi!');
    
    // Promise
    // Hi!
    // resolved
    上面代码中,Promise 新建后立即执行,所以首先输出的是Promise。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完
    才会执行,所以resolved最后输出。
    

4. 调用resolve或reject并不会终结 Promise 的参数函数的执行

	```
	new Promise((resolve, reject) => {
	  resolve(1);
	  console.log(2);
	}).then(r => {
	  console.log(r);
	});
	// 2
	// 1
	上面代码中,调用resolve(1)以后,后面的console.log(2)还是会执行,并且会首先打印出来。这是因为立即 resolved 的 Promise
	 是在本轮事件循环的末尾执行,总是晚于本轮循环的同步任务。
	
	一般来说,调用resolve或reject以后,Promise 的使命就完成了,后继操作应该放到then方法里面,而不应该直接写在resolve或
	reject的后面。所以,最好在它们前面加上return语句,这样就不会有意外。
	new Promise((resolve, reject) => {
	  return resolve(1);
	  // 后面的语句不会执行
	  console.log(2);
	})
	```
5. 如果 Promise 状态已经变成resolved,再抛出错误是无效的

	```
	const promise = new Promise(function(resolve, reject) {
	  resolve('ok');
	  throw new Error('test');
	});
	promise
	  .then(function(value) { console.log(value) })
	  .catch(function(error) { console.log(error) });
	// ok
	上面代码中,Promise 在resolve语句后面,再抛出错误,不会被捕获,等于没有抛出。因为 Promise 的状态一旦改变,就永久保持该状
	态,不会再变了。
	```
6. Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个catch语句捕获。

	```
	getJSON('/post/1.json').then(function(post) {
	  return getJSON(post.commentURL);
	}).then(function(comments) {
	  // some code
	}).catch(function(error) {
	  // 处理前面三个Promise产生的错误
	});	
	```	
	
7. Promise 内部的错误不会影响到 Promise 外部的代码,通俗的说法就是“Promise 会吃掉错误”。
	
	```
	const someAsyncThing = function() {
	  return new Promise(function(resolve, reject) {
	    // 下面一行会报错,因为x没有声明
	    resolve(x + 2);
	  });
	};
	
	someAsyncThing().then(function() {
	  console.log('everything is great');
	});
	
	setTimeout(() => { console.log(123) }, 2000);
	// Uncaught (in promise) ReferenceError: x is not defined
	// 123
	```
8. Promise.prototype.finally():方法用于指定不管 Promise 对象最后状态如何,都会执行的操作

   finally方法总是会返回原来的值
   

// resolve 的值是 undefined Promise.resolve(2).then(() => {}, () => {})

// resolve 的值是 2
Promise.resolve(2).finally(() => {})

// reject 的值是 undefined
Promise.reject(3).then(() => {}, () => {})

// reject 的值是 3
Promise.reject(3).finally(() => {})

9. Promise.all()   

p的状态由p1、p2、p3决定,分成两种情况。

(1)只有p1、p2、p3的状态都变成fulfilled,p的状态才会变成fulfilled,此时p1、p2、p3的返回值组成一个数组,传递给p的回调函数。

(2)只要p1、p2、p3之中有一个被rejected,p的状态就变成rejected,此时第一个被reject的实例的返回值,会传递给p的回调函数。

10.如果作为参数的 Promise 实例,自己定义了catch方法,那么它一旦被rejected,并不会触发Promise.all()的catch方法。

   	const p1 = new Promise((resolve, reject) => {
 	  resolve('hello');
 	})
 	.then(result => result)
 	.catch(e => e);
 	
 	const p2 = new Promise((resolve, reject) => {
 	  throw new Error('报错了');
 	})
 	.then(result => result)
 	.catch(e => e);
 	
 	Promise.all([p1, p2])
 	.then(result => console.log(result))
 	.catch(e => console.log(e));
 	// ["hello", Error: 报错了] 
 	上面代码中,p1会resolved,p2首先会rejected,但是p2有自己的catch方法,该方法返回的是一个新的 Promise 实例,p2指向的
 	实际上是这个实例。该实例执行完catch方法后,也会变成resolved,导致Promise.all()方法参数里面的两个实例都会resolved,
 	因此会调用then方法指定的回调函数,而不会调用catch方法指定的回调函数。
 	如果p2没有自己的catch方法,就会调用Promise.all()的catch方法。   


11.Promise.race():只要p1、p2、p3之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给p的回调函数。

12.Promise.resolve():有时需要将现有对象转为 Promise 对象

立即resolve()的 Promise 对象,是在本轮“事件循环”(event loop)的结束时执行,而不是在下一轮“事件循环”的开始时。

 setTimeout(function () {
   console.log('three');
 }, 0);
 
 Promise.resolve().then(function () {
   console.log('two');
 });
 
 console.log('one');
 
 // one
 // two
 // three 
 上面代码中,setTimeout(fn, 0)在下一轮“事件循环”开始时执行,Promise.resolve()在本轮“事件循环”结束时执行,
 console.log('one')则是立即执行,因此最先输出。
13.Promise.reject():方法也会返回一个新的 Promise 实例,该实例的状态为rejected。

Promise.reject()方法的参数,会原封不动地作为reject的理由,变成后续方法的参数。这一点与Promise.resolve方法不一致。
   
 const thenable = {
   then(resolve, reject) {
     reject('出错了');
   }
 };
 
 Promise.reject(thenable)
 .catch(e => {
   console.log(e === thenable)
 })
 // true

14.Promise.try(f):不知道或者不想区分,函数f是同步函数还是异步操作,但是想用 Promise 来处理它。

 const f = () => console.log('now');
 Promise.resolve().then(f);
 console.log('next');
 // next
 // now
 上面代码中,函数f是同步的,但是用 Promise 包装了以后,就变成异步执行了。
 
 const f = () => console.log('now');
 Promise.try(f);
 console.log('next');
 // now
 // next
 
 Promise.try就是模拟try代码块,就像promise.catch模拟的是catch代码块。
15.

 Promise.resolve()
   .then(() => {
     return new Error('error!!!')
   })
   .then((res) => {
     console.log('then: ', res)
   })
   .catch((err) => {
     console.log('catch: ', err)
   })
   //then: Error: error!!!
 at Promise.resolve.then (...)
 at ...

.then 或者 .catch 中 return 一个 error 对象并不会抛出错误,所以不会被后续的 .catch 捕获,需要改成其中一种:

return Promise.reject(new Error('error!!!'))

throw new Error('error!!!')

16..then 或者 .catch 的参数期望是函数,传入非函数则会发生值穿透

 Promise.resolve(1)
   .then(2)
   .then(Promise.resolve(3))
   .then(console.log) //1
17..then 的第二个处理错误的函数捕获不了第一个处理成功的函数抛出的错误, 而后续的 .catch 可以捕获之前的错误。 或者是链式调用的下一个then里面的第二个处理函数

 Promise.resolve()
   .then(function success (res) {
     throw new Error('error')
   }, function fail1 (e) {
     console.error('fail1: ', e)
   })
   .catch(function fail2 (e) {
     console.error('fail2: ', e)
   })
   
 //fail2: Error: error
 at success (...)
 at ...

 或者是
 Promise.resolve()
   .then(function success1 (res) {
     throw new Error('error')
   }, function fail1 (e) {
     console.error('fail1: ', e)
   })
   .then(function success2 (res) {
   }, function fail2 (e) {
     console.error('fail2: ', e)
   })
18.执行顺序:同步 >> process.nextTick >> promise.then >> setTimeout >> setImmediate