Preface 🎃
Promises are to be made.
Let’s get one togetherconventionOk, “when you lose weight, I will be your girlfriend”, if you fail, then…
Since then I’ve been trying to lose weight…
Success reducing weight😊 : Let’s go to see the beautiful scenery 💕
Failed to lose weightThe 😔 :It’s okay. I see what you’re doing. I want you to be my boyfriend
Main content 🎃
- Promise vs. asynchronous programming
Front knowledge
Why asynchronous programming?
Js is built on the concept of a single threaded event loop. Single threading means that only one piece of code can be executed at a time. That’s the thing about it. So it works for manipulating dom trees.
The event loop is an internal processing thread of the JS engine that monitors code execution and manages job queues.
But there are other situations where we have to wait and wait if code A is time consuming, but the experience is not what we want.
Because it doesn’t affect the execution of my next piece of code. So we want to execute the next piece of code B while we’re waiting. Then we need to make an appointment. That is, the agreement, for fear of it too long to forget. In the future I will do through this agreement.
let promise = new Promise(function(resolve, reject) {
console.log("Promise");
resolve();
});
// Promise is a promise.
// Even after many years, I can use this convention to call the then method to do things,
// If you succeed, do this; if you fail, do that. If the middle is gone, throw an error
promise.then(function() {
console.log("Resolved.");
},function(){
console.log();
}).catch(error){
conole.log('error',error)
};
Copy the code
The browser itself sets up some time-consuming tasks that need to be executed asynchronously
For example: the timer thread HTTP requests page rendering
Additional knowledge:
-
A browser can have multiple processes
-
Each TAB page is a process, a process can be multiple threads, including JS thread, rendering thread and so on
Review the background of asynchronous programming
The first: the event model
When we write a click event, an event is fired, and the handler for that event is added to the end of a job queue. Waiting for execution.
let button = document.getElementById("myBtn");
button.onclick = function(event) {
console.log("Clicked");
};
Copy the code
Second: callback mode
Node.js uses an asynchronous callback, error first, where a new job is added to the end of the job queue. The following code shows the callback pattern.
readFile("example.txt".function(err, contents) {
// New assignment
if (err) {
throw err;
}
console.log(contents);
});
console.log("Hi!");
Copy the code
Third: solve callback hell
The following is a description of Promise to solve this problem, 🤔 Are there any other solutions? (You can leave a comment in the comment section)
Promise with asynchronous programming 🎃
Step 1: Simply implement a Promise
let promise = new Promise(function(resolve, reject) {
/ / 1
console.log("Promise");
resolve();
});
promise.then(function() {
// 3 A
console.log("Resolved.");
});
/ / 2
console.log("Hi!");
Copy the code
// Promise
// Hi
// Resolved
Copy the code
Solution:
-
The promise executor executes first
-
The then () method adds the function A to the end of the job queue
-
Execute the print statement log(‘Hi’)
-
Execute function A in the queue
Promise’s life cycle
- Pending status: pending (not knowing what the result is)
- This is very depressing. Once you know the result, there are two kinds:
Promise method (not one expand, you can query the use method)
-
Promise.then()
-
Promise.catch()
-
Promise.resolve()
-
Promise.reject()
Each of the above methods can be executed separately, as in the following example
let promise = Promise.reject(42);
promise.catch(function(value) {
console.log(value); / / 42
});
Copy the code
Take a look at the promise.all () and promise.race () tests and let’s analyze how they differ
let promise1 = new Promise(function(reslove,reject){
setTimeout(function () {
console.log('Pass 3');
reslove(3)},3000)});let promise2 = new Promise(function(reslove,reject){
setTimeout(function () {
console.log('Pass 1');
reslove(1)},2000)});/ / all tests
Promise.all([promise1,promise2]).then(result= >{
console.log('The result of all is',result);
}).catch(error= >{
console.log(error);
});
/ / race test
Promise.race([promise1,promise2]).then(result= >{
console.log('The result of race is',result);
}).catch(error= >{
console.log(error);
});
Copy the code
Race () returns the value 1, and all() returns the value [3,1]. Promise2 ();
Extended thinking 🤔 : What do they do about returning an error, or throwing an error? (Comments are welcome)
Promise error handling in different environments
- The actuator error ❌
let promise = new Promise(function(resolve, reject) {
throw new Error("I want an error!");
});
promise.catch(function(error) {
console.log(error.message); // "I want to report error!"
})
Copy the code
In this case, the error is caught in the executor processing and thrown
- Promise is rejected in Node.js and the browser
When a Promise is rejected and there is no REJECT handler, the unhandledrejection event is emitted. This can happen under Windows, but it can also happen in workers. This is useful for debugging fallback error handling.
let promise1;
process.on("unhandledRejection".function(reason, promise) {
console.log(reason.message); // "Error!"
console.log(promise1 === promise); // true
});
promise1 = Promise.reject(new Error("Error!"));
Copy the code
// Error!
//true
Copy the code
This should serve as a topic, and you are welcome to discuss any related issues in the comments section.
Promise Asynchronous programming development practices
Sharp sword 1🔪 : use good chain call
Does the front-end interface have such a scenario?
The result of interface 1 is used as a parameter to request interface 2 and the result of interface 2 is used as a parameter to request interface 3
new Promise(function(reslove,reject){
// Operation: request interface 1
// Return the result of interface 1
reslove('Interface 1 result')
}).then(res= >{
// Get the result for interface 1
// Operation: request interface 2
// Return the result of interface 2
reslove('Interface 2 result')
}).then(res1= >{
// Get res1(interface 2 result)
// Operation: request interface 3
// Return the result of interface 3
reslove('Interface 2 result')
}).catch(error= >{
console.log(error);
})
Copy the code
Sharp sword 2🔪 : Take advantage of promise.all () and promise.race ()
Does the front-end interface have such a scenario?
** Request interface 3 with the result of interface 1 and the result of interface 2
let promise1 = new Promise(function(reslove,reject){
// Interface 1 requests
reslove('Interface 1 result')});let promise2 = new Promise(function(reslove,reject){
// Interface 2 requests
reslove('Interface 2 result')});// Request interface 3
Promise.all([promise1,promise2]).then(result= >{
// the result of interface 1,2 is: result
// Request interface 3
}).catch(error= >{
console.log(error);
});
Copy the code
Does the front-end interface have such a scenario?
** Request interface 3 with the result of interface 1 or interface 2
let promise1 = new Promise(function(reslove,reject){
// Interface 1 requests
reslove('Interface 1 result')});let promise2 = new Promise(function(reslove,reject){
// Interface 2 requests
reslove('Interface 2 result')});// Request interface 3
Promise.race([promise1,promise2]).then(result= >{
// The result of interface 1 or 2 is: result (get the fastest request)
// Request interface 3
}).catch(error= >{
console.log(error);
});
Copy the code