Consider a scenario in which multiple network requests are issued within a short period of time after the user clicks the refresh button quickly. In order to retain only the latest request, we need to mask the callback that was previously requested and not refresh the page multiple times due to the different order of the asynchronous callback.
The idea here is to save the current context each time the API is requested (a unique identifier is ok), and determine if the return should be kept when it is received.
let context;
refresh() {
context = {};
new Promise((resolve, reject) = > {
let currentContext = context;
post('xxx', {name: 'kale'})
.then((json) = > {
if (context === currentContext) {
resolve(json)
} else {
reject("CANCELED");
}
})
.catch((json) = > {
if (context === currentContext) {
reject(json);
} else {
reject("CANCELED");
}
})
}
).then((json) = > {
// success
}).catch((reason) = > {
if(reason ! = ="CANCELED") {
// error}}); }Copy the code
- This scenario is the last of many requests for retention in a short period of time
- If you want to terminate the callback, you can simply empty the context
- If you want the current asynchronous callback to be unique, you can add an isLoading flag