当前位置:网站首页>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)
})
边栏推荐
- Addition, deletion, modification and query of handwritten ORM (object relationship mapping)
- [leetcode] most elements [169]
- Splunk audit setting
- 用matlab调用vs2015来编译vs工程
- QT qsplitter splitter
- Editor Caton
- Higher order operation of bits
- Methods to solve the tampering of Chrome browser and edeg browser homepage
- Freshman learning sharing
- 首批 | 腾讯云完成国内首个云原生安全成熟度评估
猜你喜欢

Introduction to the latest plan of horizon in April 2022

QT qsplitter splitter

Set right click to select vs code to open the file

The motivation of AES Advanced Encryption Protocol

Uniapp wechat login returns user name and Avatar

Xiaopeng P7 had an accident and the airbag did not pop up. Is this normal?

Go language sqlx library operation SQLite3 database addition, deletion, modification and query

力扣刷题(2022-6-28)

數據分析學習記錄--用EXCEL完成簡單的單因素方差分析

从底层结构开始学习FPGA----Xilinx ROM IP的定制与测试
随机推荐
从底层结构开始学习FPGA----Xilinx ROM IP的定制与测试
Strictly abide by the construction period and ensure the quality, this AI data annotation company has done it!
設置單擊右鍵可以選擇用VS Code打開文件
boot actuator - prometheus使用
详解Promise使用
2016. 增量元素之间的最大差值
Tronapi wave field interface - source code without encryption - can be opened twice - interface document attached - packaging based on thinkphp5 - detailed guidance of the author - July 1, 2022 08:43:
Motivation du Protocole de chiffrement avancé AES
Data analysis learning records -- complete a simple one-way ANOVA with Excel
海思 VI接入视频流程
阿里云有奖体验:如何使用 PolarDB-X
Introduction to the latest plan of horizon in April 2022
Redis 过期策略+conf 记录
World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection
Performance optimization - rigorous mode
Lambda表达式:一篇文章带你通透
Jerry's prototype has no touch, and the reinstallation becomes normal after dismantling [chapter]
Golang interview finishing three resumes how to write
Value sequence < detailed explanation of daily question >
C#中Linq用法汇集