Promise
new Promise( function(resolve, reject) {...} /* executor */ );
executor是带有 resolve 和 reject 两个参数的函数 ,promise构造函数执行的时候执行executor,resolve被调用promise状态改为fullilled,reject被调用状态改为rejected。
executor抛出exception,promise状态改为rejected,返回值被忽略。
简单例子
let res = function (x) { console.log("resolve"+x) } let rej = function (x) { console.log("reject"+x) } let a = function (res,rej) { var x = Date.now() if(x%2===0){ res(x)//双数执行resolve,Promise状态改为resolve }else{ rej(x)//单数执行reject,Promise状态改为reject } } new Promise(a).then(res,rej)
链式调用
function add(input) { return new Promise(function (res,rej) { if(Date.now()%2===0){ throw 123 } console.log('add'+input+input) setTimeout(res,500,input+input) console.log('over') }) } add(1).then(add).then(add).then(add).then(add) .catch(function () { console.log('error') })//串行执行,任何任务失败则不再继续并执行错误处理函数。 .finally(function () { console.log('all over') })//finally始终执行
Promise.resolve/reject
function a() { return Promise.resolve('xxx')//返回一个状态未fullfilled的promise对象,括号中为传入resolve的参数 } a().then(function (b) { alert(b) }) function a() { return Promise.reject('rrrr')//返回一个状态未rejected的promise对象,括号中为传入reject的参数 } a().catch(function (b) { alert(b) })
Promise.race/all
var p1 = new Promise(function (resolve, reject) { console.log(1) setTimeout(resolve, 500, 'P1'); }); var p2 = new Promise(function (resolve, reject) { console.log(2) setTimeout(resolve, 600, 'P2'); }); // 同时执行p1和p2,并在它们都完成后执行then: Promise.all([p1, p2]).then(function (results) { console.log(results); // 获得一个Array: ['P1', 'P2'] }); var p1 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, 'P1'); }); var p2 = new Promise(function (resolve, reject) { setTimeout(resolve, 600, 'P2'); }); Promise.race([p1, p2]).then(function (result) { console.log(result); // 'P1' });//将获得结果'P1'。p2仍在继续执行,但执行结果将被丢弃。