Preface:
Anyone who has done front-end development knows thatJavaScriptIt is a single-threaded language, and the browser only allocates toJSA main thread is used to execute tasks, but can only execute one task at a time. These tasks form a task queue to queue for execution; however, some tasks are time-consuming, such as network requests, event monitoring, and timers. If these very time-consuming tasks are allowed to queue for execution one by one, the program execution efficiency will be very low, and it may even cause the page to be faked. Therefore, the browser has opened up new threads for these time-consuming tasks, mainly including http request thread, browser event trigger thread, and browser timing trigger. However, these tasks are all asynchronous, which involves the asynchronous callback operation process developed by the front-end. The front-end uses Async/Await and Promise to handle asynchronous callback operations.
Moreover, during front-end related interviews, interviewers usually ask aboutPromiseRelated usage questions, and even some related issues will be published in the written testPromiseand setTimeout execution result, which showsPromiseThe use of the information is a very important knowledge point for front-end development. Then let's share about this blog postPromiseknowledge points related to the use of the
1. First of all, you need to know why you need to use Promise syntax?
IntroducingPromise
Before, let’s first understand the features of JavaScript. Those who engage in front-end development know that JS is a traditional single-thread programming. The program runs in it are synchronous and there is only one main thread. However, with the development of technology, in order to solve the defects in the early stage, the idea of asynchronous is introduced, that is, the execution of an asynchronous process will no longer have a sequential relationship with the original sequence, which solves the defect of low execution efficiency caused by synchronous execution. In one sentence, asynchronous means sending a child thread from the main thread to complete the task.
Let’s take a look at Promise. Promise is a new addition to ES6. It is a class provided by ES6. Its main purpose is to handle complex asynchronous tasks well, but it is not supported by any browser. For example, some old browsers do not support it. Only browsers with Safari 10 and Windows Edge 14 and above have begun to support ES6 features.
Promise is used as an alternative callback function execution and is used as a processing method for asynchronous operations. It is a solution to the problem of nested callback functions when JS is executed asynchronously. Promise controls the function execution process more concisely. The Promise object actually represents the final success or failure of an asynchronous operation, as well as the result value, that is, a proxy value, which is an asynchronous callback solution in ES6.
The value of the Promise proxy is actually unknown, and the state is dynamically mutable. Therefore, there are three types of states of the Promise object: in progress, end, and failure. When it runs, it can only go from progress to failure, or from progress to success. Use a Promise object to run asynchronous code through synchronous expressions.
- ①pending:Initial state, neither successful nor failed;
- ②fulfilled:The operation ended successfully;
- ③rejected:Operation failed.
How to construct a Promise? Here is a brief example of constructing a Promise:
new Promise(function (resolve, reject) { // Things to do... });
Construct a new one from abovePromise
The object does not seem to see how it handles complex asynchronous tasks well, so the next step is the core operation of Promise.
2. Next, let’s learn about Callback Hell
Callback hell is also called callback nesting or function confusing calls. In layman's terms, it is necessary to send three network requests, the third request depends on the result of the second request, and the second request depends on the result of the first request. Continuously increasing nested use.
Disadvantages of callback functions:
It is very laborious and difficult for developers to read, which is not conducive to troubleshooting errors, and they cannot directly return, etc.like:
setTimeout(() => { (1) setTimeout(() => { (2) setTimeout(() => { (3) },3000) },2000) },1000)
3. Finally, it is also the highlight of this chapter, the basic use of Promise
The Promise constructor has only one parameter, which is a function. After construction, this function will be run asynchronously, so we call it the starting function. The starting function, that is, the constructor of the Promise, has two parameters: resolve and reject. These two parameters represent the result of an asynchronous operation, that is, the state of success or failure of the Promise.
When Promise is constructed, the starting function will be executed asynchronously; resolve and reject are functions, where calling resolve means everything is normal, reject is called when an exception occurs.
- ①Asynchronous operation is successful, call the resolve function and change the state of the Promise object to fulfilled.
- ②Asynchronous operation fails, call rejected function and change the state of the Promise object to rejected.
To give an example of usage, the more standardized way is to encapsulate the Promise into a function and return a Promise at the same time.As shown below:
const delay = (millisecond) => { return new Promise((resolve, reject)=>{ if (typeof millisecond != 'number') reject(new Error(‘Must benumbertype')); setTimeout(()=> { resolve(`Delay${millisecond}Output in milliseconds`) }, millisecond) }) }
In the above example, we can see that Promise has two parameters: resolve and reject. resolve: Turn asynchronous execution from pending to resolve (successfully returned), which is a function execution return; reject: see the name means "rejection", and changes from request to "failure", which is a failure result that the function can execute, and it is recommended to return an error new Error(), which is clearer and more standardized.
(I) Resolve function
If the incoming right or wrongPromise
, data of the basic data type returns a successful Promise; if the incoming Promise, the result of the object determines the return result value of resolve.
let obj =new Promise((resolve,reject)=>{ resolve(‘yes'); }); //1. If the data of non-promise and basic data type is passed in, the successful promise will be returned. let p1= ('123') //2. If the incoming Promise is passed, the result of the object determines the return result value of resolve. let p2 = (obj); //3.Nested use let p3 = ((('abc'))); (p3);
(II) rejected function
, the return is always failedPromise。
let p = (123123); let p2 = ('abc'); let p3 = (('ok')); (p3);
(III) Promise API
Several commonly used methods in the Promise API are: then, catch, finally, all, race, etc. The specific usage methods are as follows.
1. then
Then specify a successful or failed callback to the current Promise. Then the data in the Promise resolved obtained in the Promise is returned and a Promise is continued to be provided; the result returned by the then method is determined by the then specified callback function.
Examples are as follows:
let p=new Promise((resolve,reject)=>{ resolve(‘yes') }) (value=>{ (value) //The value here is the yes above},reason=>{ (reason) })
2. catch
catch specifies the failed callback, and returns the failed result.
Examples are as follows:
let p =new Promise((resolve,reject)=>{ reject('fail! '); }) (value=>{},reason=>{ (reason); }) (reason=>{ (reason) })
3. finally
Finally used to perform the finishing work. Regardless of whether the state of the Promise is successful or failed, after executing the callback function, it will finally find the last callback function to execute.
Examples are as follows:
(function(){ // Finally, the code that will be executed})
4.
When multiple Promise tasks are executed together, if all succeed, a new Promise is returned. If one of them fails, a failed Promise object is returned.
Examples are as follows:
let p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(‘yes'); }, 1000); }); let p2 = ('ok'); let p3 = ('Oh no'); //Alllet result = ([p1, p2, p3]); (result);
5.
When multiple Promise tasks are executed simultaneously, the result of the Promise task that ends first is returned. Regardless of whether it is successful or failed in the end, it is popular: first come first served.
Examples are as follows:
let p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(‘yes'); }, 1000); }); let p2 = new Promise((resolve, reject) => { setTimeout(() => { resolve('ok'); }, 500); }); let result = ([p1, p2]); (result); //p2 ok
4. Finally
Through this article, you have fully mastered its use and principles for the use of Promise in front-end JS development? If readers have a good grasp of the content of this article, then in the future, whether in the actual development process or in the job interview, the knowledge points involving Promise will be easy. The importance of Promise will not be discussed here.
This is the article about the detailed explanation of Promise in JavaScript. For more related Promise content in JavaScript, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!