简单的理下Promise使用场景,
Promise.resolve();
Promise.reject();
Promise.all();
Promise.all() 使用注意事项
1.all 中接收一个可迭代的参数, 如数组和字符串
2.如果该参数为空 则Promise.all同步返回一个resolve;
3.all中如果接收的参数是promise对象,则当有一个promise是reject时,则Promise.all的状态为 rejected, 失败的, 如果所有的promise对象都已经resolve, 则返回状态为 fulfilled 成功
4.如果all中接收参数为非promise对象,则会忽略,但是仍然会返回 参数
手动实现Promise对象
function _Promise(fn) {
const sucArr = [], errArr = [];
// status 有三个值 pending, fulfilled, rejected, 默认为 pending
let status = 'pending', value = null, reason = null;
function resolve(data) {
setTimeout(() => {
status = 'fulfilled';
value = data;
sucArr.forEach(callback => {
callback(value);
});
})
}
function reject(data) {
setTimeout(() => {
status = 'rejected';
reason = data;
errArr.forEach(callback => {
callback(reason);
});
})
}
_Promise.prototype.then = function(fulfilled, rejected) {
return new _Promise(function(resolve, reject) {
function suc(data) {
const ret = typeof fulfilled === 'function' ? fulfilled(data) : data;
if(ret && typeof ret['then'] === 'function') {
ret.then(function(data){
resolve(data);
});
}else{
resolve(ret);
}
}
function err(data) {
const err = typeof rejected === 'function' ? rejected(data) : data;
reject(err);
}
if(status === 'pending'){
sucArr.push(suc);
errArr.push(err);
}else if(status === 'fulfilled') {
suc(value)
}else{
err(reason)
}
})
};
_Promise.prototype.catch = function(rejected) {
return new _Promise(function(resolve, reject) {
function err(data) {
const ret = typeof rejected === 'function' ? rejected(data) : data;
if(ret && typeof ret['catch'] === 'function') {
ret.catch(function(datas) {
reject(datas)
})
}else{
reject(ret)
}
}
if(status === 'pending') {
errArr.push(err)
}else{
err(reason);
}
})
};
try{
fn(resolve, reject);
}catch(e) {
reject(e);
}
}