Preface: this is the first article to digg gold to write, looking back on the PREVIOUS USE of CSDN, blog garden these blog sites, I think the technical atmosphere of digg gold is more suitable for my standard after 95 haha. The people in the boiling point are quite interesting, hopefully the circle can get better and better. Today we are going to study the Promise object, ha ha ha, hope to help you in need of help friends.
What is Promise?
English interpretation
I’ll make a promise.
A document explaining
1. A Promise object is used for asynchronous computation. 2. A Promise instance represents a value that is, will be, or will never be used.Copy the code
Explain by purpose:
- First, promises are used for asynchronous computation
- Second, asynchronous operations can be queued and executed in the desired order, returning the expected results.
- Promises can be passed and manipulated between objects to help us deal with queues.
Does it make sense to write this? Yes, this little thing is the order in which asynchronous functions are transformed into synchronous methods. In my Promise domain, everyone is happy. If I put you in the first place, you have to do it in the first place.
Why is there a Promise?
We all know that JS was originally created to process forms, mainly to manipulate DOM. So many operations in JS are asynchronous, the main purpose of asynchronous operation is to avoid interface freezing, here is to introduce a concept, synchronous task and asynchronous task execution order, this I believe everyone is familiar, because JS is an Event polling mechanism, the English name Event Loop.
Event polling
To elaborate on this event polling, JS is a single-threaded language, which means that only one task can be executed at a time. Now there is a file, and when the code is executed from top to bottom, it will encounter synchronous tasks as well as asynchronous tasks. Let’s introduce a few concepts. The thread that currently executes a synchronous task is called the main thread, and an asynchronous task also has a place for it, called a task queue. Synchronous tasks are executed in the same order as if you were waiting in line to get a vaccine, but there was only one doctor, and that was the order of execution from first to last without cutting in line. Asynchronous task execution order, is equivalent to a bunch of people now go to dozen vaccine, or is it just a doctor, but a few people don’t have my mobile phone, can’t show the health code, this group of people in line to him, the doctor asked him to id, but he didn’t need to go home with, get back to continue lined up to make vaccine. There is no one to carry it with us than asynchronous tasks, home is the task queue, all asynchronous when implemented first in order to mount to the task queue, task queue follow the principle of first in first out, wait until after the synchronization task has been completed, the main thread will ask task queue have to perform asynchronous tasks, Asynchronous tasks are performed on a first-in, first-out basis. Of course, there are micro and macro tasks for asynchronous tasks, which we will discuss later.
Node. Js
- Node.js is competitive because of its non-blocking and high concurrency
- Support for non-blocking high concurrency must rely on asynchronous events
- A large number of operations rely on callback functions
Drawback of callback function “callback hell”
let resA = [] let resB = [] function a(){ axios.get('urla').then(res =>{ resA = res }) } function b(resA){ Axios.get ('urlb',{params: resA}). Then (res =>{resB = res}) function c(resB){axios.get('urlc',{params: ResB}). Then (res =>{return res})} function a(){ axios.get('urla').then(res =>{ resA = res if(resA){ axios.get('urlb',{ params: ResA}). Then (res =>{resB = res if(resB){axios.get('urlc',{params: resB}). Then (res =>{return res})}})})}Copy the code
Imagine if you had 100 interfaces to nest calls, the code would be very readable and maintainable, and the code would look bad, so Promise objects were created to solve the headache of callback hell.
Promise,
Promise to write
New Promise((reslove,reject)=>{// New Promise((reslove,reject)) Reject () // Either method can pass the arguments of an asynchronous operation to the later THEN and catch methods. Reject the second callback or catch the callback}). Then ((success)=>{// call the callback on success}). Catch ((error)=>{// call the callback on failure}).Copy the code
As you can see here, the Promise is a proxy object that has no direct relationship to the original operation, and it avoids more callbacks by introducing a callback.
The state of the Promise
- When we initially new a Promise object it belongs to
pending
State, which is to be determined - When the operation succeeds, the Promise changes to
fulfilled
Is the operation succeeded - When the operation fails, the Promise changes to
rejected
Is that the operation fails
Promise state changes
- The Promise triggers when the state changes
.then
or.catch
The later callback - Once a Promise’s status changes, it doesn’t change again.
Two-step execution example
console.log('start')
new Promise((reslove,reject) =>{
setTimeout(()=>{
reslove('hello')
},2000)
}).then((value)=>{
console.log(value)
return new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove('world')
},2000)
})
}).then((value)=>{
console.log(value + ' world')
})
Copy the code
The result is: start Hello world
What happens to the completed Promise implementation then
console.log('start') let promise = new Promise((reslove,reject) =>{ setTimeout(()=>{ console.log('fulfilled') Reslove (' Hello world')},2000)}) setTimeout(()=>{promise.then((value)=>{console.log(value)})}, 3000)Copy the code
Completed Promise objects can be stored in variables and used anywhere in the current Promise scope.
What if the.then function doesn’t return a new Promise object
console.log('start') new Promise((reslove,reject) =>{ setTimeout(()=>{ reslove('hello') },2000) }).then((value){ console.log(value) console.log('everyone') (function(){ return new Promise((reslove,reject)=>{ setTimeout(()=>{ console.log('promise niub') reslove('biu biu biu') },2000) }) }()) return false }).then((value)=>{ console.log(value + ' world') })Copy the code
The result of the above code is: Start Hello everyone false world promise niub The code then continues to execute, waiting until the execution is complete before executing the suspended Promise object. In a Promise, if you do not return a Promise object directly, it will execute the following code, and returning false will not stop the code from executing further down the line. If. Then does not return a value and does not return a specific value, then value will show undipay.
State response function. Then. Catch
- A new Promise object can be returned from the state response function, as well as other values
- If a new Promise is returned, then the next level
.then()
Will be executed after the new Promise state changes - If it doesn’t return a Promise object, then the next level
.then()
Will execute directly .then()
The second parameter catches an error from the previous Promise object,.catch()
The catch is the error of the entire chain call of the Promise, and the priority of the two is determined by the order in which they occur, with whichever comes first having higher priority
Promise common functions
Promise.all()
- Accepts an array as an argument
- The array can be anything else, or it can be a Promise object, and only promises will wait for the state to change
- If the received value is not a Promise object, it is passed directly to the next state function
- When all the child Promises are complete, the Promise is complete, and the return value is an array of all the values
- On any failure, the Promise fails and returns the result of the first failed child Promise
Promise.race()
- This is similar to promise.all (), except that a Promise is completed as long as one child is fulfilled
Promise used at work
Wrap the callback as a Promise
getApiData = function(){ return new Promise((reslove,reject)=>{ axios.get('url') reslove(data) }).then(data =>{ ... })}Copy the code
This ensures that the first asynchronous request is completed before the next operation, which is often used in the workplace.
I will talk about syntactic candy and async await in ES7 later. Even if I have syntactic candy, I will learn Promise first. I hope this article can help you.