SoFunction
Updated on 2025-03-01

Understand the ES6 Promise extension method

ES6 has added a Promise object. It is processed in then when it succeeds, and in catch if it fails. However, sometimes, we need to do something when it succeeds or fails, such as hiding loading, recording logs, etc. Let's take the browser-side ajax request as an example, and we use axios (it is based on Promise):

("/").then(()=>{
 //Processing logic ...
 ("Request End")
 hideLoading();
}).catch(()=>{
 ("Request End")
 hideLoading();
})

Such code is very redundant. Every time this time I miss jQuery a little:

$.get("/").done(()=>{
 //Processing logic}).always(()=>{
 ("Request End")
 hideLoading();
})

es6-promise-always has made an extension of the functions of ES6, making it support always, and supports node and browser at the same time.

use

1. Installation

npm install es6-promise-always --save

2. Introduce and use

require("es6-promise-always")
("/").then(()=>{
 //Processing logic}).always(()=>{
 ("Request End")
 hideLoading();
})

always(data, error)

  • data: resolved data.
  • error: reject data.

Tips

Don't worry that this will make your program fat! es6-promise-always are very small. When I first realized, I always went in the wrong direction and I was lost. Github address:/wendux/es6-promise-always

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.