JavaScript异步操作
1. Promise.all()和Promise.race() 并行调用异步操作
两个函数均用于并行调用多个异步操作使用
- All:两个异步操作都resolve之后调用then()
1 2 3 4 5 6 7 8 9 10
| var p1 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, 'P1'); }); var p2 = new Promise(function (resolve, reject) { setTimeout(resolve, 600, 'P2'); });
Promise.all([p1, p2]).then(function (results) { console.log(results); });
|
- Race:最快的异步操作resolve后调用then()
1 2 3 4 5 6 7 8 9 10
| 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 (results) { console.log(results); });
|