This article mainly introduces the ES6 Promise extension always method. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
ES6 adds a Promise object, which is processed in then in case of success and in catch in case of failure. But sometimes, we need to do something whether it succeeds or fails, such as hiding loading. , record logs, etc. Below we take the browser-side ajax request as an example. We use axios (it is based on Promise):
axios.get("/").then(()=>{ //处理逻辑 ... console.log("请求结束") hideLoading(); }).catch(()=>{ console.log("请求结束") hideLoading(); })
Such code is very verbose Remain. Every time at this time, I miss jQuery a little:
$.get("/").done(()=>{ //处理逻辑 }).always(()=>{ console.log("请求结束") hideLoading(); })
es6-promise-always is an expansion of the functions of ES6, making it support always and node at the same time. and browser.
Use
1.Install
npm install es6-promise-always --save
2.Introduce and use
require("es6-promise-always") axios.get("/").then(()=>{ //处理逻辑 }).always(()=>{ console.log("请求结束") hideLoading(); })
always(data, error)
data: resolved data.
error: reject data.
Tips
Don’t worry this will make your program fat! es6-promise-always is very small. When I first started to realize "always", I took the wrong direction, and Xinhao found my way back. Github address: https://github.com/wendux/es6-promise-always
Related recommendations:
ES6 Promise brief introduction
The above is the detailed content of Detailed explanation of ES6 Promise extension always method instance. For more information, please follow other related articles on the PHP Chinese website!