基本使用和原理
Promise.all
和Promise.race
Promise
标准Promise
语法
function loadImg(src) {
const promiss = new Promise((resolve, reject) => {
let img = document.createElement('img');
img.onload = function () {
resolve(img);
};
img.onerror = function () {
reject()
};
img.src = src;
});
return promiss;
}
let src = 'img_url';
const result = loadImg(src);
result.then(img => {
console.log(img.width);
}, () => {
console.log('failed');
});
result.then(img => {
console.log(img.height);
});
问题解答
new Promiss()
实例,而且要return
new Promise
时要传入函数,函数有resolve
、reject
两个参数resolve()
,失败时执行reject()
then
监听结果异常捕获
//规定:then只接受一个参数,最后统一用catch捕获异常
result.then(function (img) {
console.log(img.width);
}).then(function (img) {
console.log(img.height);
}).catch(function (ex) {
// 最后统一catch
console.log(ex);
});
Promise.all
&Promise.race
//Promise.all接收一个promise对象的数组
//待全部完成之后,统一执行success
Promise.all([result1, result2]).then(datas => {
//接收到的datas是一个数组,依次包含了多个promise返回的内容
console.log(datas[0]);
console.log(datas[1]);
});
//Promise,race接收一个包含多个promise对象的数组
//只要有一个完成,就执行success
Promise.race([result1, result2]).then(data => {
//data即最先执行完成的,promise的返回值
console.log(data);
});
pending
、fullfilled
、reject
pending
pending
变为fullfilled
,或者pending
变为rejected
then
Promise
实例必须实现then
这个方法then()
必须可以接收两个函数作为参数then()
返回的必须是一个Promise
实例