当前位置:网站首页>Explain promise usage in detail
Explain promise usage in detail
2022-07-02 23:08:00 【Little IKey】
Promise
introduce Promise
We call a function , This function sends a network request ( We can use timers to simulate );
If the network request is sent successfully , Then inform the caller that the transmission is successful , And return the relevant data to the past ;
If sending a network request fails , Then inform the caller that the sending failed , And tell the error message ;
function requestData(url, successCallback, failtureCallback) {
// Simulate network requests
setTimeout(() => {
if (url === 'codewhy') {
let names = ['abc', 'bcd', 'nba']
successCallback(names)
} else {
let errMessage = ' request was aborted '
failtureCallback(errMessage)
}
}, 3000)
}
requestData('codewhy',
// success
(res) => {
console.log(res)
// Failure
}, (err) => {
console.log(err)
})
In the above code , We can actually solve the problem after the request function gets the result , Get the corresponding callback , But it has two main problems :
- We need to design the callback function ourselves , Name of callback function 、 The use of callback functions, and so on ;
- For different people , Different frameworks design different schemes , Then we must be patient to look at other people's source code or documents , So that we can understand how to use this function ;
PromiseAPI
Promise Is a class , Can be translated into commitment 、 Promise 、 time limit ;
When we need to give the caller a commitment : When I call back the data for you , I can just create one Promise The object of
Through new establish Promise Object time , We need to pass in a callback function , We call it executor
- This callback function will be executed immediately , And pass in two other callback functions resolve、reject;
- When we call resolve When calling back a function , Will execute Promise Object's then Method ;
- When we call reject When calling back a function , Will be executed immediately Promise Object's catch Method ;
Promise Code structure of :
const promise = new Promise((resolve,reject) =>{
// pending state : undetermined
resolve(" success ")
reject(" Failure ")
})
// fulfilled state : Has been cashed in
promise.then(res=> {
console.log(res)
})
//rejected state : Rejected
promise.catch(err=>{
console.log(err)
})
above Promise Using process , We can divide it into three stages :
- undetermined (pending): The initial state , Neither cash , There was no rejection ; When executed executor When the code is in , In this state ;
- Has been cashed in (fulfilled) : Means the operation is completed successfully ; Yes resolve when , In this state ;
- Rejected (rejected): Means the operation failed ; Yes reject when , In this state ;
Promise Refactoring request
With Promise, We can refactor the previous code :
function requestData(url){
return new Promise((resolve,reject) =>{
setTimeout(() =>{
if(url === "https://www.csdn.net"){
resolve(" success ")
}else{
reject(" Failure ")
}
},1000)
})
}
Executor
Executor Is to create Promise A callback function that needs to be passed in , This callback function will be executed immediately , And two parameters are passed in :
new Promise((resolve,reject) => {
console.log("executor Code ")
})
Usually we will be in Executor Determine our Promise state :
- adopt resolve, Can cash (fulfilled)Promise The state of , We can also call it resolved (resolved);
- adopt reject, Can refuse (reject)Promise The state of
Be careful : Once the status is determined , Then it is unchangeable
After we call resolve When , If resolve The value passed in is not itself a Promise, Then it will Promise The state of becomes cashed (fulfilled)
After that, we call reject when , There will be no response anymore ( It's not that this line of code doesn't execute , But can't change Promise The state of )
resolve The difference between different values
Situation 1 : If resolve Pass in a normal value or object , Then this value will be taken as then Parameters of the callback
new Promise((resolve,reject) =>{
resolve('normal message')
}).then(res=>{
},err=>{
})
Situation two : If resolve What is passed in is another Promise, So this new Promise Will decide the original Promise state :
const newPromise = new Promise((resolve,reject) => {
resolve(" I am the new value ")
})
new Promise((resolve, reject) => {
resolve(newPromise)
}).then(res => {
console.log("res:",res)
}, err => {
console.log("err:",err)
})
Situation three : If resolve What is passed in is an object , And this object has implementation then Method , Then it will implement the change then Method , And according to then The result of the method Promise The state of :
new Promise((resolve,reject) => {
const obj = {
then:function(resolve,reject){
resolve("resolve message")
}
}
resolve(obj)
}).then(res => {
console.log("res:",res)
}, err => {
console.log("err:",err)
})
then Method - Take two parameters
then The method is Promise A method on the object : It's actually on Promise On the prototype of Promise.prototype.then
then Method accepts two arguments :
- fulfilled Callback function for : When the state becomes fulfilled Function that will be called back when ;
- reject Callback function for : When the state becomes reject Function that will be called back when ;
promise.then(res=>{
console.log(res)
},err =>{
console.log(err)
})
// Equivalent to :
promise.then(res =>{
console.log(res)
}).catch(err =>{
console.log(err)
})
then Method
then Method can be called multiple times
One Promise Of then Methods can be called many times ;
Each time we call, we can pass in the corresponding fulfilled Callback ;
When Promise The state of the state becomes fulfilled When , These callback functions will be executed ;
then(res =>{
console.log(res)
})
promise.then(res =>{
console.log('res2:',res)
})
promise.then(res =>{
console.log('res3:',res)
})
then Return value of method
then The method itself is determined by the return value , Its return value is one Promise, So we can make chain calls :
however then Method Promise What kind of state is it ?
Promise There are three states :
When then The callback function itself in the method is executed , So it's in pending state ;
When then Method returns a result , So it's in fulfilled state , And will take the result as resolve Parameters of ;
- Situation 1 : Returns a normal value ;
- Situation two : Return to one Promise;
- Situation three : Return to one thenable Value ;
When then Method throws an exception , So it's in reject state ;
catch Method
catch Multiple calls to method
catch Method is also Promise A method on the object : It is also placed in Promise On the prototype of Promise.prototype.catch
One Promise Of catch Method can be called multiple times ;
Each time we call, we can pass in the corresponding reject Callback ;
When Promise The state of the state becomes reject When , These callback functions will be executed ;
promise.catch(err=>{
console.log(err)
})
promise.catch(err=>{
console.log(err)
})
catch Method - Return value
in fact catch Method also returns a Promise Object's , therefore catch Method, we can continue to call then Methods or catch Method :
const promise = new Promise((resolve,reject) =>{
reject('rejected message')
})
promise.then(res=>{
},err=>{
console.log(err)
return new Promise((resolve,reject) =>{
resolve('js Human force ')
// reject(" Hello ")
})
}).then(res =>{
console.log('res',res) // js Human force
},err=>{
console.log("err",err)
})
finally Method
finally Is in ES9(ES2018) A new feature in : No matter what Promise The object becomes fulfilled still reject state , Code that is ultimately executed
finally Methods do not accept parameters , Because no matter what's ahead fulfilled state , still reject state , It will execute .
const promise = new Promise((resolve,reject) =>{
resolve("helloworld")
// reject("reject message")
})
promise.then(res =>{
console.log("res:",res)
}).catch(err =>{
console.log(err)
}).finally(()=>{
console.log(" I did ") // Whether it's resolve still reject It will be carried out
})
resolve Class method
Ahead then、catch、finally Methods all belong to Promise Instance method of , It's all stored in Promise Of prototype Upper
Now let's learn Promise Class method of .
Promise.resolve The usage of is equivalent to new Promise , And perform resolve operation :
const promise = Promise.resolve({
name:'why',age:19})
console.log(promise)
// amount to
const promise2 =new Promise((resolve,reject) =>{
resolve({
name:'why',age:19})
})
console.log(promise2)
resolve Parameter form :
- Situation 1 : A parameter is an ordinary value or object
- Situation two : The parameter itself is Promise
- Situation three : The parameter is one thenable
reject Class method
reject The method is similar to resolve Method , It's just going to be Promise The state of the object is set to reject state
Promise.reject The usage of is equivalent to new Promise , It just calls reject:
const promise = Promise.reject('rejected message')
// amount to
const promise2 = new Promise((resolve,reject) =>{
reject("rejected message")
})
promise2.then(res =>{
}).catch(err=>{
console.log(err)
})
Promise.reject The parameters passed in, no matter what form , Will act directly as reject State parameters are passed into catch Of
all Class method
Promise.all effect : Will be multiple Promise Wrapped together to form a new Promise;
new Promise The status is determined by all of the packages Promise Joint decision :
When all Promise The state becomes fulfilled In the state of , new Promise Status as fulfilled, And will put all Promise The return value of consists of an array ;
When you have one Promise Status as reject when , new Promise Status as reject, And will be the first reject As a parameter
// Create multiple Promise
const p1 = new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve('11111')
},1000)
})
const p2 = new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve('222222')
},2000)
})
const p3 = new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve('333333')
},5000)
})
// all Promise All become fulfilled
// all Class methods also return Promise
Promise.all([p1,p2,p3,'abc']).then(res =>{
console.log(res)
}).catch(err=>{
console.log(err)
})
result :
allSettled Method
all The method has a flaw : When one of them Promise become reject In the state of , new Promise Will immediately become the corresponding reject state .
So for resolve Of , And dependence is in pending State of Promise, We can't get the corresponding results ;
stay ES11(ES2020) in , Add a new API Promise.allSettled:
Change the method will be in all Promise All have results (settled), No matter when fulfilled, still rejected when , Will have the final state ;
And the whole Promise The result is certain fulfilled Of ;
// Create multiple Promise
const p1 = new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve('11111')
},1000)
})
const p2 = new Promise((resolve,reject) =>{
setTimeout(()=>{
// resolve('222222')
reject("helloworld")
},2000)
})
const p3 = new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve('333333')
},5000)
})
Promise.allSettled([p1,p2,p3,'abc']).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
result :
It can be seen that except for the second one rejected, The rest are fulfilled
race Method
If there is a Promise With the result , We just want to decide the final new Promise The state of , Then you can use race Method :
race It's a competition , The meaning of competition , Representing multiple Promise Compete with each other , Who has the result first , Then use whose results ;
// Promise.race
// Create multiple Promise
const p1 = new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve('11111')
},1000)
})
const p2 = new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve('222222')
// reject("helloworld")
},2000)
})
const p3 = new Promise((resolve,reject) =>{
setTimeout(()=>{
resolve('333333')
},5000)
})
// race As long as there is one Promise become fulfilled ends
Promise.race([p1,p2,p3]).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
边栏推荐
- psnr,ssim,rmse三个指标的定量分析
- Start from the bottom structure to learn the customization and testing of FPGA --- Xilinx ROM IP
- Methods to solve the tampering of Chrome browser and edeg browser homepage
- PotPlayer设置最小化的快捷键
- Share 10 JS closure interview questions (diagrams), come in and see how many you can answer correctly
- Typical case of data annotation: how does jinglianwen technology help enterprises build data solutions
- AES高级加密协议的动机阐述
- SQL进阶语法
- 深度剖析数据在内存中的存储----C语言篇
- [Solved] Splunk: Cannot get username when all users are selected“
猜你喜欢
Innovation strength is recognized again! Tencent security MSS was the pioneer of cloud native security guard in 2022
Configuration clic droit pour choisir d'ouvrir le fichier avec vs Code
C#中Linq用法汇集
深度剖析数据在内存中的存储----C语言篇
Construction of Hisilicon 3559 universal platform: rotation operation on the captured YUV image
`Usage of ${}`
Minimum spanning tree
mysql重置密码,忘记密码,重置root密码,重置mysql密码
QT qsplitter splitter
最小生成树 Minimum Spanning Tree
随机推荐
Boot actuator - Prometheus use
剑指 Offer II 099. 最小路径之和-双百代码
boot actuator - prometheus使用
Go语言sqlx库操作SQLite3数据库增删改查
深度剖析数据在内存中的存储----C语言篇
1px pixel compatibility of mobile terminal, 1px border
20220527_数据库过程_语句留档
xshell配置xforward转发火狐浏览器
[leetcode] number of palindromes [9]
`Usage of ${}`
[npuctf2020]ezlogin XPath injection
[Yangcheng cup 2020] easyphp
Xiaopeng P7 had an accident and the airbag did not pop up. Is this normal?
海思3559万能平台搭建:在截获的YUV图像上画框
Construction of Hisilicon 3559 universal platform: draw a frame on the captured YUV image
MySQL queries nearby data And sort by distance
[Solved] Splunk: Cannot get username when all users are selected“
从2022年Q1财报看携程的韧性和远景
Strictly abide by the construction period and ensure the quality, this AI data annotation company has done it!
容器化技术在嵌入式领域的应用