是什么

异步编程的一种解决方案

Promise 状态

var promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
  	Math.random() * 100 > 60 ? resolve('ok') : reject('no')
  })
})
promise.then(val => {
	console.log(val);
}, reason => {
	console.log(reason);
})

Promise 特性

then 的返回值作为下一次 then 的执行参数

var promise = new Promise(function(resolve, reject){
  setTimeout(function(){
  	Math.random() * 100 > 60 ? resolve('ok') : reject('no')
  })
})
promise.then(val => {
	console.log(val);
  return 1
}, reason => {
	console.log(reason);
  return 2
}).then(val => {
	console.log('then2-', val);
}, reason => {
	console.log('then2-', reason);
})

Untitled

var promise = new Promise(function(resolve, reject) {
  setInterval(function() {
  	Math.random() * 100 > 60 ? resolve('ok') : reject('no')
  })
})
promise.then(val => {
	console.log(val);
  return new Promise((resolve, reject) => {
  	resolve('new promise')
  })
}, reason => {
	console.log(reason);
  return 2
}).then(val => {
	console.log('then2-', val);
}, reason => {
	console.log('then2-', reason);
})

Untitled

resolve 导致抛出错误会被 reject 接收

var promise = new Promise((resolve, reject) => {
	resolve(a);
})

promise.then((val) => {
	console.log('resolve', val);
}, (reason) => {
	console.log('reject', reason);
})

Untitled

catch 等同于:then 第一个参数为 null ,第二个参数为 reject 的回调函数

var promise = new Promise((resolve, reject) => {
	resolve(a);
})

promise.then(null, (reason) => {
	console.log('reject', reason);
})

promise.catch((reason) => {
	console.log('reject', reason);
})

Untitled

pormise 状态一旦固化,就无法再改变

var promise = new Promise((resolve, reject) => {
	resolve('ok');
  console.log(a); // 这个报错因为状态固化,无法被捕获
})

promise.then((val) => {
	console.log('res', val);
}).catch((reason) => {
	console.log('reject', reason);
})