Home > Web Front-end > JS Tutorial > body text

Detailed explanation of ES6 Promise extension always method instance

小云云
Release: 2018-01-31 13:28:59
Original
2144 people have browsed it

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();
})
Copy after login

Such code is very verbose Remain. Every time at this time, I miss jQuery a little:


$.get("/").done(()=>{
 //处理逻辑
}).always(()=>{
 console.log("请求结束")
 hideLoading();
})
Copy after login

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
Copy after login

2.Introduce and use


require("es6-promise-always")
axios.get("/").then(()=>{
 //处理逻辑
}).always(()=>{
 console.log("请求结束")
 hideLoading();
})
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!