Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对象。
1 2 3 4 5
| new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 1000); });
|
es5中使用异步操作
1 2 3 4 5 6 7 8 9 10 11 12 13
| { let ajax = function (callback) { console.log('执行1'); setTimeout(function () { callback && callback.call(); }, 1000); } ajax(function () { console.log('timeout1'); }); }
|
使用Promise 方式执行异步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| { let ajax = function () { console.log('执行2'); return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 1000); }); }; ajax().then(() => { console.log('timeout2'); }) }
|
多个步骤的操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| { let ajax = function () { console.log('执行3'); return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 1000); }); }; ajax() .then(() => { console.log('timeout3-1'); return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 1000); }); }) .then(() => { console.log('timeout3-2'); return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, 1000); }); }) .then(() => { console.log('timeout3-3'); }) }
|
串行问题 的异常错误的捕获
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| { let ajax = function (num) { console.log('执行4'); return new Promise((resolve, reject) => { if (num > 5) { resolve(); } else { throw new Error('出错了'); } }); }; ajax(6) .then(() => { console.log('正常'); }).catch((err) => { console.log(err); }); ajax(3) .then(() => { console.log('正常'); }).catch((err) => { console.log(err); }); }
|
Promise.all ,Promise.race 的形式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| { function loadImg(src) { return new Promise((resolve, reject) => { let img = document.createElement('img'); img.src = src; img.onload = () => { resolve(img); }; img.onerror = (err) => { reject(err) } }); } function showImgs(imgs) { imgs.forEach((img) => { document.body.appendChild(img); }); } Promise.all([ loadImg('http://url/1.jpg'), loadImg('http://url/2.jpg'), loadImg('http://url/3.jpg') ]).then(showImgs); Promise.race([ loadImg('http://url/1.jpg'), loadImg('http://url/2.jpg'), loadImg('http://url/3.jpg') ]).then(showImgs); }
|