2. 实现Promise.finally
Sunny-117 opened this issue · comments
/**
* 无论成功还是失败都会执行回调
* @param {Function} onSettled
*/
Promise.prototype.finally = function (onSettled) {
return this.then(
(data) => {
onSettled(); // 实现了收不到参数了
return data;
},
(reason) => {
onSettled();
throw reason;
}
);
// finally函数 返回结果应该是无效的
}
/******test finally*******/
// 无论什么结果,都会运行
const pro = new Promise((resolve, reject) => {
resolve(1);
});
const pro2 = pro.finally((d) => {
console.log("finally", d); // 收不到d参数
// 本身不改变状态,但是抛出一个错误,数据就会变成它的错误
// throw 123;
return 123; //不起作用
});
setTimeout(() => {
console.log(pro2);
});
Promise.prototype.myfinally = function (cb) {
return this.then(
async (data) => {
await Promise.resolve(cb(data));
return data;
},
async (err) => {
await Promise.resolve(cb(err));
throw err;
}
);
};
const pro = new Promise((resolve, reject) => {
resolve(1);
});
const pro2 = pro.myfinally((d) => {
console.log("finally", d); // 收不到d参数
// 本身不改变状态,但是抛出一个错误,数据就会变成它的错误
// throw 123;
return 123; //不起作用
});
Promise.prototype.myfinally = function (callback) {
return this.then(
async (res) => {
await callback();
return res; //finally本质起传递的作用,这里的res是上一个then函数的返回值
},
async (err) => {
await callback();
throw err;
}
);
};
Promise.resolve(123)
.then((res) => {
console.log(res); //123
return Promise.reject(456);
})
.myfinally(() => {
console.log("finally");
return "finally本身不返回值";
})
.then(
() => {},
(err) => {
console.log(err); //123
return 789;
}
)
.myfinally(() => console.log("finally"))
.then((res) => console.log(res)); //789
Promise.prototype.Finally = function (fn) {
return new Promise((resolve, reject) => {
this.then((data) => {
fn();
resolve(data);
}).catch((err) => {
fn();
reject(err);
});
});
};