当前位置:网站首页>【ES6】Promise
【ES6】Promise
2022-04-21 22:04:00 【Xiao Shen Yue】
1. Promise The meaning of
Promise Is a solution to asynchronous programming . It's simply a container , It holds an event that will end in the future ( This is usually an asynchronous operation ) Result . grammatically ,Promise It's an object , You can get the message of asynchronous operation from him .Promise Provide uniform API, Various asynchronous operations can be handled in the same way .
Promise Objects have the following two characteristics
(1) The state of the object is not affected by the outside world .Promise The object represents an asynchronous operation , There are three states :pending( Have in hand ),fulfilled( Have succeeded ) and reject( Failed ). Only results of asynchronous operations , You can decide which state you are in , No other operation can change this state . This is also Promise( promise ) The origin of the name .
(2) Once the status changes , It won't change , You can get that at any time .Promise Object state changes , There are only two possibilities : from pending Turn into fulfilled And from the pending Turn into rejected. As long as those two things happen , The state is frozen , It won't change , It's going to stay that way , This is called resolve( Have to finalize the design ). If change has already happened , You again to Promise Object to add a callback function , And you'll get that immediately . With the event (Event) Completely different , The characteristic of the event is : If you miss it , To listen again , You don't get results .
With Promise object , The asynchronous operation can be expressed as a synchronous operation flow , Avoid layers of nested callback functions . Besides ,Promise Objects provide a uniform interface , Makes it easier to control asynchronous operations .
Promise There are also some disadvantages . First , Can't cancel Promise, As soon as a new one is built, he will execute it immediately , Unable to cancel . Secondly, if the callback function is not set ,Promise An error thrown internally , It's not reflected externally , Third , When in pending In the state of , It is impossible to know at what stage ( Just started or almost finished )
2. Basic usage
ES6 Regulations ,Promise An object is a constructor , Used to generate Promise example
The following code creates a Promise example
const promise = new Promise(function(resolve,reject){
//...
if(/* Asynchronous operation succeeded */){
resolve(value)
}else{
// Asynchronous operation failed
reject(error)
}
})
Promise The constructor takes a function as an argument , The two parameters of this function are resolve and reject. They are two functions , from JavaScript The engine provides , Don't deploy yourself .
resolve The delta function is going to be , take Promise Object state from “ Hang in the air ” become “ success ”( From pending Turn into resolve), Called when the asynchronous operation succeeds , And the result of the asynchronous operation , Passed as a parameter ;reject The delta function is going to be , take Promise Object state from “ Hang in the air ” become “ Failure ”( From pending Turn into rejected), Called when an asynchronous operation fails , Error reported by asynchronous operation , Passed as a parameter .
Promise After instance generation , It can be used then Methods specify resolved State and rejected Callback function for state .
promise.then(function(res){
//success
},function(error){
//error
})
then Method can take two callback functions as parameters , The first callback function is Promise The state of the object changes to resolved Called when the , The second callback function is Promise The state of the object changes to rejected Called when the . among , The second function is optional , It is not necessary to provide . Both functions receive Promise Object as a parameter .
Promise A simple example
function timeout(ms) {
return new Promise((resolve,reject) => {
setTimeout(resolve,ms,'done')
})
}
timeout(100).then(value=>{
console.log(value)
})
Promise Execute as soon as new
let promise = new Promise(function(resolve,reject){
console.log('promise')
resolve()
})
promise.then(function(){
console.log('resolved')
})
console.log('hi')
//promise
//hi
//resolve
In the above code ,Promise Create a new one and execute it immediately , So the first output is ’promise’. Then the output ‘hi’,then The callback function specified by the method will not be executed until all synchronization tasks in the current script are executed , therefore resolved The final output .
Nesting uses
If the resolve Functions and reject Function with arguments , Then their arguments are passed to the callback function .reject The arguments to a function are usually Error Instance of object , Indicates the error thrown ;resolve The parameters of the function are in addition to normal values , It could be another Promise example , Like this :
const p1 = new Promise(function(resolve,reject){
//...
})
const p2 = new Promise(function(resolve,reject){
//...
resolve(p1)
})
In the above code p1 and p2 All are Promise Example , however p2 Of resolve Methods will p1 As a parameter , That is, the result of an asynchronous operation is to return another asynchronous operation .
Be careful : At this time p1 The state of will be passed to p2, in other words ,p1 The state of p2 The state of . If p1 The state of is pending, that p2 The callback function will wait p1 The state of change ; If p1 It's already resolved or rejected, that p2 The callback function of will execute immediately .
3. Promise.prototype.then()
Promise Instances have then Method , in other words ,then The method is defined in the prototype object Promise.prototype Upper . What it does is Promise Instance adds a callback function when the state changes .then The first parameter of the method is resolved Callback function for state , The second parameter ( Optional ) yes rejected Callback function for state .
then Method returns a new one Promise object ( Be careful : Not the original one Promise example ). Therefore, you can use a chain call , That is, a then The method is called again later then Method .
getJSON('/posts.json').then(function(json){
return json.post
}).then(function(post){
//...
})
The above code is used then Method , Two callback functions are specified in turn . After the first callback function is executed , Will return the result as a parameter , Pass in the second callback function .
It's a chain then, You can specify a set of callback functions to be called in order , At this time , The previous callback function , It is possible to return to a Promise object ( Asynchronous operation ), The latter callback function , Will wait for this Promise The state of the object changes , Will be called .
4. Promise.prototype.catch()
Promise.prototype.catch() The method is .then(null,rejection) or .then(undefined,rejection) Another name for , Used to specify the callback function when an error occurs .catch Method returns promise object , So it can be called later then Method
getJSON('/posts.json').then(function(posts){
//...
}).catch(function(error){
console.log(error)
})
In the above code ,getJSON Method returns a Promise object , If the object state changes to resolved, It will call then Callback function specified by method ; If an asynchronous operation throws an error , The state is going to be zero rejected, Will call catch Callback function specified by method , Handle this error . in addition ,then Callback function specified by method , If an error is thrown while running , Will also be catch Methods to capture .
p.then(val => console.log(val))
.catch(err => console.log(err))
// Equate to
p.then(val => console.log(val))
.then(null,err => console.log(err))
Example :
const promise = new Promise(function(resolve,reject){
throw new Error('test')
})
promise.catch(function(error){
console.log(error)
})
//Error: test
In the above code ,promise Make a mistake , I was catch Method to capture , The following two expressions are equivalent to the above
// Writing a
const promise = new Promise(function(resolve,reject){
try{
throw new Error('test')
} catch(e){
reject(e)
}
})
promise.catch(function(error){
console.log(error)
})
// Write two
const promise = new Promise(function(resolve,reject){
reject(new Error('test'))
})
promise.catch(function(error){
console.log(error)
})
Compare the above two ways of writing , You can find reject The role of methods , It's the same as throwing an error
Be careful : If Promise The state has become resolved, It's invalid to throw another error .
const promise = new Promise(function(resolve,reject){
resolve('ok')
throw new Error('test')
})
promise.then(function(res){
console.log(res)
}).catch(error){
cosole.log(error)
}
// ok
The above code ,Promise stay resolve Statement behind , Throw the error again , Will not be captured , Is equal to not throwing . because Promise Once the state of , Keep that state forever , It won't change again .
Promise The error of the object is “ Bubbling ” nature , It's going to go all the way back , Until it is captured , in other words , Mistakes are always next catch Statements capture . Generally speaking , Not in then Method definition Reject Zha UN Counter callback function ( namely then Second parameter of ), Always used catch Method
// Recommend writing
promise
.then(function(data){
//...
})
.catch(function(error){
//...
})
With the traditional try/catch The difference between code blocks is , If not used catch Method specifies the callback function for error handling ,Promise An error thrown by an object is not passed to outer code , There will be no reaction
5. Promise.prototype.finally()
finally Method is used to specify whether Promise What is the final state of the object , Will perform the operation . The method is ES2018 Introducing standard .
promise
.then(res => {
...})
.catch(err => {
...})
.finally(() => {
...})
No matter in the above code promise What's the final state , The execution of the then or catch After the specified callback function , It will be carried out finally Callback function specified by method
finally Method does not take any arguments , That means there's no way to know , Ahead Promise The state is fulfilled still rejected. This shows that ,finally Operation in method , It should be state independent , Don't depend on Promise The results of the implementation of .
6. Promose.all()
Promise.all Method is used to add more than one Promise example , Pack into a new one Promise example
const p = Promise.all([p1,p2,p3])
In the above code ,Promise.all Method takes an array as an argument ,p1,p2,p3 All are Promise example , If not , I'll call the following promise.resolve Method , Convert parameter to Promise example , Further processing .(Promise.all Method can be an array , But must have Iterator Interface , And every member returned is Promises example )
p The status of the p1,p2,p3 decision , There are two cases
(1) Only p1,p2,p3 The state of fulfilled,p The state of fulfilled, here p1,p2,p3 The return value of consists of an array , Pass to p Callback function for .
(2) as long as p1,p2,p3 One of them was rejected,p The state of rejected, At this time, the first was rejected The return value of the instance of , Will pass to p Callback function for .
7. Promise.race()
Promise.race Again, multiple Promise example , Pack into a new one Promise example .
const p = Promise.race([p1, p2, p3]);
In the above code , as long as p1、p2、p3 One of the examples is the first to change the State ,p The state of . The first to change Promise The return value of the instance , It is passed to the p Callback function for .
Promise.race Method parameters and Promise.all The method is the same , If not Promise example , I'll call the following Promise.resolve Method , Convert parameter to Promise example , Further processing .
Here is an example , If no result is obtained within the specified time , will Promise The state of becomes reject, Otherwise it becomes resolve.
const p = Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('request timeout')), 5000)
})
]);
p
.then(console.log)
.catch(console.error);
In the above code , If 5 In seconds fetch Method cannot return result , Variable p The state of will become rejected, triggering catch Callback function specified by method .
8. Promise.resolve()
Sometimes you need to convert an existing object to Promise object ,Promise.resolve The method plays this role .
const jsPromise = Promise.resolve($.ajax('/whatever.json'));
The above code will jQuery Generated deferred object , Turn into a new Promise object .
Promise.resolve It's equivalent to the following .
Promise.resolve('foo')
// Equivalent to
new Promise(resolve => resolve('foo'))
Promise.resolve The parameters of the method are divided into four cases .
(1) The parameter is one Promise example
If the parameter is Promise example , that Promise.resolve No changes will be made 、 Returns the instance intact .
(2) The parameter is one thenable object
thenable Object means having then Object of method , For example, the following object .
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
Promise.resolve Method converts the object to Promise object , And then immediately thenable Object's then Method .
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
let p1 = Promise.resolve(thenable);
p1.then(function(value) {
console.log(value); // 42
});
In the above code ,thenable Object's then After method execution , object p1 The state of becomes resolved, And immediately execute the last one then Callback function specified by method , Output 42.
(3) The parameter does not have then Object of method , Or not an object at all
If the argument is a primitive value , Or one that doesn't then Object of method , be Promise.resolve Method returns a new one Promise object , Status as resolved.
const p = Promise.resolve('Hello');
p.then(function (s){
console.log(s)
});
// Hello
The above code generates a new Promise Instance of object p. Because of the string Hello It's not an asynchronous operation ( The judgment method is that the string object does not have then Method ), return Promise The status of an instance from a lifetime achievement is resolved, So the callback function will execute immediately .Promise.resolve Method parameters , It will be passed to the callback function at the same time .
(4) No parameters
Promise.resolve() Method is allowed to be called without parameters , Just return one resolved State of Promise object .
therefore , If you want to get one Promise object , The more convenient method is to call directly Promise.resolve() Method .
const p = Promise.resolve();
p.then(function () {
// ...
});
The variables in the code above p It's just one. Promise object .
It should be noted that , immediately resolve() Of Promise object , It's in this round “ The event loop ”(event loop) At the end of , Not in the next round “ The event loop ” At the beginning of .
setTimeout(function () {
console.log('three');
}, 0);
Promise.resolve().then(function () {
console.log('two');
});
console.log('one');
// one
// two
// three
In the above code ,setTimeout(fn, 0) In the next round “ The event loop ” Start with ,Promise.resolve() In the current round “ The event loop ” Execute at the end ,console.log('one') It's immediate execution , So output first .
9. Promise.reject()
Promise.reject(reason) Method also returns a new Promise example , The state of the instance is rejected.
const p = Promise.reject(' Something went wrong ');
// Equate to
const p = new Promise((resolve, reject) => reject(' Something went wrong '))
p.then(null, function (s) {
console.log(s)
});
// Something went wrong
The above code generates a Promise Instance of object p, Status as rejected, The callback function executes immediately .
Be careful ,Promise.reject() Method parameters , Will do it exactly as it is done reject The reason of , Becomes an argument to a subsequent method . This is related to Promise.resolve Inconsistent methods .
const thenable = {
then(resolve, reject) {
reject(' Something went wrong ');
}
};
Promise.reject(thenable)
.catch(e => {
console.log(e === thenable)
})
// true
In the above code ,Promise.reject The parameter of the method is a thenable object , After execution , Back catch The argument to the method is not reject Throw the “ Something went wrong ” This string , It is thenable object .
版权声明
本文为[Xiao Shen Yue]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204212156117425.html
边栏推荐
- 搭建本地Canal中间件进行数据迁移 —— 从缓存击穿得到的启发
- The @ select annotation is used in the mapper of mybtais, and the if annotation is used
- Outil CSV - YAML en ligne
- 攻防世界 mfw
- [MySQL] solve the problem of MAC accessing MySQL server on windows
- 外包学生管理系统的架构文档
- 【ES6】函数的扩展
- ROS机器人从起点到终点(四)蓝桥云实践复现
- GAMES101 Lec6 反走样与深度缓冲
- 【ES6】let和const命令
猜你喜欢

Push to origin/master was rejected:报错解决办法

Huayun actively responded to the anti epidemic call of Hefei high tech Zone: practicing social responsibility and contributing to the strength of science and technology enterprises

解放双手,推荐一款阿里开源的低代码工具,YYDS~

什么?你们公司还没有将JVM初始和最大堆内存大小设置为相同值?

【VSCode】调试器debugger详细使用手册

Live555 learning

面试必刷算法TOP101之背包九讲篇 TOP14
![[canvas] basic drawing and use](/img/c2/8781a269863db93124467e92035895.png)
[canvas] basic drawing and use

攻防世界 mfw

UML integrated design example
随机推荐
static,const,volatile,extern,register关键字深入解析
Leetcode0785. 判断二分图(medium,二分图,DFS)
[webgl] simple tutorial
echart 写一个大屏展示圆边渐变柱状图
Mswep data NC format to TIF format
Hospital-Oriented RFID Service
因为疫情让服装行业彻底认识到了数字化转型的必要性。
【ES6】数组的扩展
【JVM】10道不得不会的JVM面试题
One plus two earphone products: charge for 10 minutes and listen to music for 20 hours
一篇彻底搞懂-->shell脚本
攻防世界 mfw
【最佳实践】巡检项:云服务器(CVM)实例本地盘类型检查
Windowns offline wsl2 installation
Because the epidemic makes the garment industry fully realize the necessity of digital transformation.
【ES6】字符串的扩展
微信小程序怎么实现商品列表跳转商品详情页功能
国产API管理神器Eolink,我爱了
外包学生管理系统的架构文档
Free your hands and recommend a low code tool open source by Alibaba, yyds~