如何编写通用的可重用promise then/catch处理程序



我有很多对json端点的调用,它们看起来像这样。这是在Vue组件的上下文中,但实际上这并不重要。所有这些处理程序所做的就是显示一条带有成功/错误的引导消息,所有智能都在服务器中。

因此,它实际上与所有console.log("it worked!")处理程序没有什么不同,只是我的处理程序需要额外的参数。

//The Vue component
let myVue = this;
axios.post(this.action_url, qs.stringify(data), config)
.then(function (response) {
// it's a bit more complicated as it looks at response contents
// for the actual message
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
});
})
.catch(function (error) {
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "failure");
});

其他地方。。。

let myVue = this;
axios.post(another_url, qs.stringify(data2), config2)
.then(function (response) {
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
});
.catch ....
})

我只想对响应和错误处理程序进行一次编码,然后重用它们。但是,因为我需要从我的执行上下文中了解一些东西,在这种情况下是myVue,所以我不能只导入一个函数并传递响应,或者我遗漏了什么?

function handleResponse(response){
// 👇💣 I need extra contextual variables, not just response
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
};

如果它起作用,我可以用它作为

axios.post(this.action_url, qs.stringify(data), config)
.then(handleResponse(response))
.catch(someErrorhandler(error));

而不是每次都重复具有完全相同内容的闭包。

来自Python,我认为curry(为函数调用预先分配一个参数,在本例中为myVue{myVue: myVue}(可以做到这一点,但如果处理程序相同,那么实现处理程序重用的惯用JS方法是什么?任何使用内置es6的东西都比引入像Lodash这样的额外依赖更可取。

您在currying方面走在了正确的轨道上:

function handleResponse(myVue) {
return function handleResponse(response){
myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
};
}

用作

axiosPromise.then(handleResponse(myVue));

最新更新