1.实例方法
p.then() 得到异步任务的正确结果
p.catch() 获取异常信息
p.finally() 成功与否都会执行
//语法
.then(function(data){
console.log(data);
})
.catch(function(data){
console.log(data);
})
.finally(function(){
console.log('finished');
});
//举例
function foo() {
return new Promise(function(resolve,reject){
setTimeout(function(){
//resolve(123);
reject('error');
},100)
})
}
foo()
.then(function(data){
console.log(data);
})
.catch(function(data){
console.log(data);
})
.finally(function(){
console.log('finished');
});
//运行结果 :
//error finished
2.对象方法
Promise.all() 并发处理多个异步任务,所有任务都执行完成才能得到结果(控制台输出一个数组)
Promise.race() 并发处理多个异步任务,只要有一个任务完成就能得到结果(控制台输出速度最快的结果)
//语法
Promise.all([p1,p2,p3]).then((result) => {
console.log(result)
})
Promise.race([p1,p2,p3]).then((result) => {
console.log(result)
})
可通过console.dir(Promise)查看Promise结构