-
Promise 对象用于表示一个异步操作的最终完成 (或失败)及其结果值。
-
promise 有静态方法:race,all,reject,resolve, allSettled, any
-
promise原型上的方法:then,catch,finally
-
一个 Promise 必然处于以下几种状态之一:
- pending:初始状态,既没有被兑现,也没有被拒绝。
- fulfilled:操作成功完成。
- rejected:操作失败。
-
例子1
var a = new Promise((resolve, reject) => {
setTimeout(() => {
resolve({a: 1});
}, 1000);
});
var b = new Promise((resolve, reject) => {
setTimeout(() => {
resolve({a: 1});
}, 1200);
});
var aa = a.then((v) => {
console.log(v, 'aa');
});
var bb = b.then((v) => {
console.log(v, 'bb');
});
var aaa = aa.then((v) => {
console.log(v, 'aaa');
});
var bbb = bb.then((v) => {
console.log(v, 'bbb');
});
Promise.all([aa, bb]).then(data => {
console.log('all', data);
});
Promise.all([a, b]).then(data => {
console.log('a b all', data);
});
- 例子2
var a = new Promise((resolve, reject) => {
setTimeout(() => {
reject({a: 1});
}, 1000);
});
var b = new Promise((resolve, reject) => {
setTimeout(() => {
reject({a: 1});
}, 1200);
});
var aa = a.then((v) => {
console.log(v, 'aa');
}).catch(() => {});
var bb = b.then((v) => {
console.log(v, 'bb');
}).catch(() => {});
var aaa = aa.then((v) => {
console.log(v, 'aaa');
})
var bbb = bb.then((v) => {
console.log(v, 'bbb');
});
Promise.all([aa, bb]).then(data => {
console.log('all', data);
});
Promise.all([a, b]).then(data => {
console.log('a b all', data);
});
- 例子3
var a = new Promise((resolve, reject) => {
setTimeout(() => {
reject({a: 1});
}, 1000);
});
var b = new Promise((resolve, reject) => {
setTimeout(() => {
reject({a: 1});
}, 1200);
});
var aa = a.then((v) => {
console.log(v, 'aa');
}).catch(() => {});
var bb = b.then((v) => {
console.log(v, 'bb');
}).catch(() => {});
var aaa = aa.then((v) => {
console.log(v, 'aaa');
})
var bbb = bb.then((v) => {
console.log(v, 'bbb');
});
Promise.allSettled([aa, bb]).then(data => {
console.log('all', data);
});
Promise.allSettled([a, b]).then(data => {
console.log('a b all', data);
});