JS 原生异步操作
支持多层异步
//ES6写法
Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => { throw reason })
);
};
//常规写法
Promise.prototype.finally = function (callback) {
var P = this.constructor;
return this.then(
function(value){
P.resolve(callback()).then(function(){
return value
})
},
function(reason){
P.resolve(callback()).then(function(){
throw reason
})
}
);
};
//使用
return new Promise(function (resolve, reject) {
$http.get('./json/xiansuotibao.json').then(function(t){
console.log('t',t)
resolve({ errno: 0, data: 'ok' })
}).catch(function(c){
console.log('c',c)
reject({ errno: 1, data: 'err' })
});
}).then(function(res){
console.log('p->',res);
//返回结果后,可以多层嵌套 return new Promise().then()
});