Promise
//返回Promise对象 function asy(a, b) { //返回成功,将值传递给resolve;反之,传给reject return new Promise(function (resolve,reject) { //异步方法 if(typeof a!=='number'||typeof b!=='number'){//判断错误 reject(new Error('no number')); } setTimeout(function () { resolve(a + b); }, 200); }); } //调用asy方法,不管有没有结果,会将结果传递给then后面的函数。then(func1(resolve),func2(reject)) asy(1,'jj') .then(function (result) { if(result>2){ return asy(result,2); } },function (err) {//捕获错误1 console.log('first-') }) .then(function (result) { if(result>4){ console.log('OK'); } }) .catch(function (error) {//捕获错误2 console.log('second'+error); });
实例1:
'use strict'; class User { constructor(name, pwd) { this.name = name; this.pwd = pwd; }; validateName(cb) { let name = this.name; return new Promise(function (resolve, reject) { setTimeout(function () { if (name === 'leo') { resolve('suc'); } else { reject('err'); } }, 200); }) }; validatePwd(cb) { let pwd = this.pwd; return new Promise(function (resolve, reject) { if (pwd === '123') { resolve('sucPwd'); } else { reject('falsePwd'); } }); } } const user=new User('leo','123'); //只验证名字 user.validateName() .then(function (suc) {//resolve console.log(suc); }) .catch(function (err) {//reject。捕捉错误 console.log(err); }); //验证账号密码 user.validateName() .then(function (suc) { return user.validatePwd();////验证账号成功后,验证密码 }) .then(function (suc) { console.log('success log') }) .catch(function (err) { console.log('false log') });
实例2:
Promise.all Promise.race 只要出现错误,就不会再执行。
'use strict'; function asyncfun(a,b) { return new Promise(function (resolve,reject) { resolve(a+b); }); } var pro=[]; //连续应用 asyncfun(1,3) .then(function (res) { pro.push(res); return asyncfun(5,7); }) .then(function (res) { pro.push(res); }); console.log(pro);//4,12 //Promise.all执行所有结果 Promise.all([asyncfun(1,3),asyncfun(5,7)]) .then(function (res) {//数组 console.log(res);//4,12。 pro和res相同 }); console.log(pro); //Promise.race执行第一个返回的结果 Promise.race([asyncfun(1,3),asyncfun(5,7)]) .then(function (res) {//数组 console.log(res);//4 });