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');
});
// 同时执行p1和p2,并在它们都完成后执行then:
Promise.all([p1, p2]).then(function (results) {
console.log(results); // 获得一个Array: ['P1', 'P2']
});
  • 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');
});
// 同时执行p1和p2,最快返回函数执行then:
Promise.race([p1, p2]).then(function (results) {
console.log(results); // 'P1'
});

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!