Reasons for Promise
Since the last asynchronous request is initiated depending on the result of the current request when writing the code in the traditional callback way… Then there is the callback hell, mainly in the messy structure of the code, not good to write, not good to read, not good to maintain, the emergence of Promise is of great significance, analysis of the implementation of Promise, you can find out the writing of the function, the transfer of parameters and other JS rules
Promise regular use
A Promise request can be in three states: Pending, Resolved, and Reject. Once you move a Promise from pending to resolved, the state cannot be changed again
Promise sync code structure: New A Promise. The Promise contains a callback function that has been bound internally. Resolve ([parameter]) and Reject ([parameter]) are the parameters of this callback function.
Promise async code structure (thenable) : The then section, which registers the resolved state callback as x in resolve(x), for example, resolve(19). The reject(x) callback function can be registered with the reject(x) callback function. For example, reject(19) is rejected (19)
Promise (catchable) : catch (rejected
new Promise((resolve,reject) = >{
setTimeout(function(){
// resolve(19)
reject(19)},1000)
}).then(data= >{
console.log(data)
console.log("data")},err= >{
console.log(err)
console.log("err1")
}).catch(err= >{
console.log(err)
console.log("err2")})// Output result:
1.If it is resolve (19), 19 data
2.If it is reject (19), 19 err1
Copy the code
In the above example, because the error message has been caught in the callback err1 is in, the next catch position will actually be a new Promise object which is resolved (or fulfilled) with data as undefined, so the error message will not be caught
Promise other apis
resolve
New Promise(resolve=>{resolve(13)})
reject
Promise. Reject (13) = new Promise(reject=>{reject(13)})
all
All is passed an iterable, and arrays are obviously. For all, the Thenable code will run when all asynchronous messages are in the Resolved state. If there is only one rejected, you have to catch it
var t1 = function(){
return new Promise((resove,reject) = >{
setTimeout(function(){
resove(1)},1000)})}var t2 = function(){
return new Promise((resove,reject) = >{
setTimeout(function(){
resove(2)},2000)})}Promise.all([t1(),t2()]).then(data= >{
console.log(data)[1, 2]
// The result corresponds to the request in the iterable type
})
Copy the code
race
Method returns a promise that is resolved or rejected once a promise in the iterator is resolved or rejected.
Promise async and await
Async and await are syntactic candies that simplify the writing of promises, make the synchronous code of the request and part of the code of the response more clear, increase the readability, and eliminate the use of THEN
Async and await are used routinely
async function test(){
await t1()
console.log("t1ok")// Prints 1 in two seconds
await t2()
console.log("t2ok")// Three seconds to print 2
}
Copy the code
Await the asynchronous response, the following code will not execute, the process relinquishes control, waits for the asynchronous response to arrive, retakes control of the controller, executes the subsequent synchronous code, and knows the next await
await 1
Note that await can only be used in async functions. Await is the state data of a Promise
Note that async returns data or Rejected’s err value
async function test2(){
await 1
//return await 1
}
test2().then(data= >{
console.log(data)//undefined
})
Copy the code
Console. log(await 1) is found to be 1, and a return is added to the code, which is equivalent to passing the state data to the new Promise generated by calling async. The final result will print 1 instead of undefined
async function test2(){
await 1
}
// The official equivalent code
async function test2(){
return Promise.resolve(1).then(data= >undefined)}Copy the code
How do async and await handle the Rejected response
By the try… Catch processing
function fn(){
return new Promise((resolve,reject) = >{
if(Math.random()<0.5){
resolve(1)}else{
reject(2)}}}async function test3(){
try {
var res = await fn()
console.log(`resolved:${res}`)}catch (error) {
console.log(`rejected:${error}`)
}
}
test3()
Copy the code
Multiple Promise and Reduce combinations
var fun1 = function(){console.log("fun1")}
var fun2 = function(){console.log("fun2")}
var fun3 = function(){console.log("fun3")}
var arrr = [fun1,fun2,fun3]
arrr.reduce((p,f) = >p.then(f),Promise.resolve())
Fun1 fun2 fun3*/
Copy the code
The initial promise.resolve () pushes the state to the final, which causes fun1, fun2, and fun3 to be run in subsequent Thenable queues
Wrap setTimeout as a Promise
The asynchracy of setTimeout is used with the old callback function, which is now wrapped as a Promise and can be used with await
function delay(ms){ return new Promise((resolve,reject)=>{ setTimeout(resolve,ms) }) } async function test4(){ await Delay (2000) console.log("2 seconds up ")} test4()Copy the code
This delay function is valid only in asynchrony