Promise对象--Mr.Emberajax
摘要json
所谓promise,简单来讲就是一个容器,里面保存着某个将来才会结束的事件(一般是一个异步操做)数组
promise对象有一下特色:promise
1. 对象的状态不受外界影响异步
2. 一旦状态改变就不会再变,任什么时候候均可以获得这个结果。async
有了promise对象,就能够将异步操做以同步操做的流程表达出来,避免了层层嵌套函数。函数
Promise.prototype.then()this
p.then((val) => console.log('fulfilled:', val)) .catch((err) => console.log('rejected', err)) //等同于 p.then((val) => console.log('fulfilled:', val)) .then(null, (err) => console.log('rejected', err))
Promise.all()spa
Promise.all将多个Promise实例包装成一个新的Promise实例。prototype
var p = Promise.all([p1, p2, p3]);
var p = Promise.all([p1, p2, p3]);
上述代码中,只要p1, p2, p3有一个实例率先改变状态,p的状态就跟着改变。那个率先改变Promise的实例的返回值就传递给p的回调函数。
Promise.resolve()
有时须要将现有的对象转为Promise对象,Promise.resolve方法就起到了这个做用。
var jsPromise = Promise.resolve($ajax('/whatever.json'));
var p = Promise.reject('出错了') //等同于 var p = new Promise((resolve, reject) => reject('出错了')
p.then(null, function(s){
console.log(s)
})
Promise.done()
不管Promise对象的回调链以then的方法仍是catch的方法结尾,只要最后一个放大抛出错误,都有可能没法捕捉到(由于Promise内部错误不会冒泡到全局)。为此咱们能够提供一个done方法,它老是处于回调链的尾端,保证抛出任何可能出现的错误。
asyncFunc() .then(f1) .catch(r1) .then(f2) .done();
Promise.prototype.done = function (onFulfilled, onRejected) { this.then(onFulfilled, onRejected) .catch(function(reason) {
//全局抛出一个错误 setTimeout(() => {throw reson}, 0); }) }
Promise.finally()
finally方法用于指定Promise对象最后状态如何都会执行的操做。他与done的区别在于,它接受一个普通的回调函数做为参数,该函数无论什么状态都会执行。
function MyPromise(fn) { var _this = this; //用来保存then传入的回调函数 this.callback = []; //处理 第一个resolve有效 this.isResolved = false; function resolve(val) { if(_this.isResolved) return; _this.isResolved = true; if(_this.callback.length > 0) { _this.callback.forEach(item => { // func && func(val) var res, cb = item.cb, resolve=item.resolve; cb && (res = cb(val)) if(typeof res === 'object' && res.then) { res.then(resolve) }else { resolve && resolve(res) } }); } } fn(resolve); } MyPromise.prototype.then = function(cb) { var _this = this; return new MyPromise(function(resolve) { _this.callback.push({ cb: cb, resolve: resolve }) }) } var p = new MyPromise(function(resolve) { console.log(1) setTimeout(function() { resolve(2) resolve(4) resolve(5) resolve(6) }, 1000) }) p.then(function(val) { console.log(val) return new MyPromise(function(resolve) { setTimeout(function() { resolve(val + 1) }, 1000) }) }).then(function(val) { console.log(val) })
打印结果
先打印1,过了一秒打印2,再过一秒打印3