当前位置:网站首页>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)
})
边栏推荐
- Higher order operation of bits
- Lc173. Binary search tree iterator
- 1px pixel compatibility of mobile terminal, 1px border
- To myself who is about to work
- Uniapp wechat login returns user name and Avatar
- `Usage of ${}`
- 设置单击右键可以选择用VS Code打开文件
- 从2022年Q1财报看携程的韧性和远景
- [chestnut sugar GIS] how does global mapper batch produce ground contour lines through DSM
- boot actuator - prometheus使用
猜你喜欢

Redis 过期策略+conf 记录

Qt QScrollArea

Lambda expression: an article takes you through

Qt QScrollArea

MySQL reset password, forget password, reset root password, reset MySQL password

创新实力再获认可!腾讯安全MSS获2022年度云原生安全守护先锋

Motivation du Protocole de chiffrement avancé AES

数据标注典型案例,景联文科技如何助力企业搭建数据方案

WebRTC音视频采集和播放示例及MediaStream媒体流解析

Configuration clic droit pour choisir d'ouvrir le fichier avec vs Code
随机推荐
[leetcode] reverse the word III in the string [557]
Typical case of data annotation: how does jinglianwen technology help enterprises build data solutions
Antd component upload uploads xlsx files and reads the contents of the files
WebRTC音视频采集和播放示例及MediaStream媒体流解析
门牌制作 C语言
归并排序详解及应用
地平线2022年4月最新方案介绍
大一学习分享
2016. 增量元素之间的最大差值
阿里云有奖体验:如何使用 PolarDB-X
antd组件upload上传xlsx文件,并读取文件内容
To myself who is about to work
Jerry's built-in shutdown current is 1.2ua, and then it can't be turned on by long pressing [chapter]
Value sequence < detailed explanation of daily question >
Share 10 JS closure interview questions (diagrams), come in and see how many you can answer correctly
Odoo13 build a hospital HRP environment (detailed steps)
4 special cases! Schools in area a adopt the re examination score line in area B!
Lambda expression: an article takes you through
[NPUCTF2020]ezlogin xPATH注入
mysql重置密码,忘记密码,重置root密码,重置mysql密码