gpt4 book ai didi

javascript - 从 Promise 中提取 .then 和 .catch

转载 作者:行者123 更新时间:2023-12-01 03:35:55 24 4
gpt4 key购买 nike

我编写了一个通用的 .js crud 对象,它包含用于与服务器通信的所有方法。不过,我想避免重复 .then 和 .catch,并且我想在外部方法中抽象该功能。

不确定我想要实现的目标是否可能。

我的代码如下:

all(url, success, fail){
return new Promise((resolve,reject) => {
_get(url)
.then((response) => {
if (response.status == 200) {
success.call(this,response);
return resolve();
}
})
.catch((error) => {
fail.call(this, error);
reject(error);
});
});}, submit, update .....

仙境期望的结果:

all(url, success, fail){
return new Promise((resolve, reject) => {
_get(url).handle(args);
});
}

最佳答案

只要避免 Promise constructor antipattern和回调,你会做得很好!

function all(url) {
return _get(url).then((response) => {
if (response.status == 200) {
return response;
}
// most likely you want to `throw` an error here?
});
}

关于javascript - 从 Promise 中提取 .then 和 .catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com