Recently, I need to write a project to encapsulate the request library, and use the Promise object to accumulate.
Promise object
To understand
The Promise object is a solution for asynchronous JavaScript operations and acts as a bridge between asynchronous operations and callback functions, replacing layers of nesting callback with a chain
state
The whole process will only be from pending to fulfilled/ Rejected, and the state is irreversible once it happens
Examples of promise
Let’s start by instantiating a Promise object
const pro = new Promise((resolve, reject) = > {
if (true) {
If the internal code succeeds, the then callback function is executed
// Pass the argument 111 when the function is successfully called
resolve(111);
} else {
// Execute a catch callback when the internal code fails
// Fail to call the function and pass the argument 222
reject(222); }});console.log("Promise object", pro);
Copy the code
On __proto__ you’ll see it has these three
Add: Promise’s.then method can pass in two callbacks: the first for the successful operation and the second for the failed one
p2.then(console.log, console.error);
Copy the code
pro
.then(
// Then's callback is accepted by resolve
// res receives arguments to a successful call
res= > {
console.log(res); })// The catch callback is accepted by reject
.catch(
// Err receives arguments to failed calls
err= > {
console.log(err); })// finally completes, executes regardless of success or failure
.finally(() = > {
console.log("Succeed and fail and execute.");
});
Copy the code
Request wrapper library example (WX applet request as an example)
// export can be exported multiple times
// export default Can export only one
export const axios = (params) = > {
// params is the parameter passed in
// export ES6 export
return new Promise((resolve, reject) = > {
//wx.request this is just for wechat appletswx.request({ ... params,// Struct out
// Basic path + request address
url: baseURL + params.url,
success: (result) = > {
// Return the core data directly
resolve(result.data.message);
// Successful callback function
},
fail: (error) = > {
reject();
// Failed callback function
},
complete: () = >{}}); })};Copy the code