1.印象
古人云:“君子一诺千金”,这种“承诺将来会执行”的对象在JavaScript中称为Promise对象。
Promise就是解决多个异步请求的问题
Promise有三种状态:Pending(进行中)、Resolved(已完成)和 Rejected(已失败)
串行异步then并行异步all竞争异步race 传递参数resolve(then)reject(catch)
2.案例
使用promise执行异步函数我们可以在promise里定义异步函数 ,then与catch分别捕获resolve与reject抛出的信息
new Promise(function (resolve, reject) {console.log('start new Promise...');var timeOut = 0.5;console.log('set timeout to: ' + timeOut + ' seconds.');setTimeout(function () {if (timeOut < 1) {console.log('call resolve()...');resolve('200 OK INFO');}else {console.log('call reject()...');reject('timeout in ' + timeOut + ' seconds.');}}, timeOut * 1000);}).then(function (r) {console.log('Done: ' + r);}).catch(function (reason) {console.log('Failed: ' + reason);});VM353:2 start new Promise...VM353:4 set timeout to: 0.5 seconds.Promise{<pending>}VM353:7 call resolve()...VM353:16 Done: 200 OK INFOsetTimeout(function, milliseconds, param1, param2, ...)
3.串行执行异步任务:then
<script>function cal(input) {return new Promise(function (resolve, reject) {setTimeout(resolve, 500, "add");console.log(input);});}function add(input) {return new Promise(function (resolve, reject) {setTimeout(resolve, 500, "cal");console.log(input);});}var p = new Promise(function (resolve, reject) {console.log('start');resolve("cal");});p.then(cal).then(add).then(cal);</script><!--start--><!--3.Promise.html:6 cal--><!--3.Promise.html:13 add--><!--3.Promise.html:6 cal-->
4.并行执行异步任务:all
var p1 = new Promise(function (resolve, reject) {setTimeout(resolve, 500, 'P1');});var p2 = new Promise(function (resolve, reject) {setTimeout(resolve, 600, 'P2');});// 同时执行p1和p2,并在它们都完成后执行then:Promise.all([p1, p2]).then(function (results) {console.log(results); // 获得一个Array: ['P1', 'P2']});
5.竞争异步执行任务:race
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执行较快,Promise的then()将获得结果'P1'。p2仍在继续执行,但执行结果将被丢弃。如果我们组合使用Promise,就可以把很多异步任务以并行和串行的方式组合起来执行。