当前位置:网站首页>Promise knowledge points
Promise knowledge points
2022-06-30 05:32:00 【Dax1_】
Preface
Most of this article is written by Ruan Yifeng ES6 Introductory tutorial , The original link is at the end of the text .
This article is a concise version of personal arrangement .
What is? Promise
Promise It's an object , From it you can get messages for asynchronous operations . Promise Provide uniform API, Various asynchronous operations can be handled in the same way .
Promise Characteristics
The state of the object is not affected by the outside world . Promise There are three states ,
pending
( Have in hand )、resolved
( Completed , also called fulfilled) andrejected
( Failed ). Only results of asynchronous operations , You can decide which state you are in , No other operation can change this state .Once the status changes , It won't change , You can get that at any time . Promise There are only two possible changes to the state of an object : from
pending
Turn intoresolved
Or frompending
Turn intorejected
. As long as those two things happen , The state will never change again .
Promise Problem solved
- Promise Asynchronous operation can be expressed as the process of synchronous operation , Avoid layers of nested callback functions , Be commonly called
Back to hell
- Promise Provide a unified interface , Make asynchronous operations easier .
Promise The shortcomings of
- Can't cancel Promise, Once it's created, it's executed immediately , Unable to cancel
- If you do not set the callback function ,Promise An error thrown internally , It's not reflected externally
- When in
pending
In the state of , It is impossible to know the current status
Basic usage
Promise An object is a constructor , Used to generate Promise example .
The following code creates a Promise example
var promise = new Promise(function(resolve, reject) {
// ... some code
if (/* Asynchronous operation succeeded */){
resolve(value);
} else {
reject(error);
}
});
Promise Takes a function as an argument , The two parameters of this parameter are resoleve
and reject
, They are two functions .
resolve
The delta function is going to be , take Promise Status from pending
Turn into resolved
, 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 Status from pending
Turn into reject
, Called when an asynchronous operation fails , The error reported by the asynchronous operation is passed as a parameter .
Promise After instance generation , Can pass then
Methods specify resolved
State and reject
Callback function for state .
promise.then(function(value) {
// success
}, function(error) {
// failure
});
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 Reject Called when the . among , The second function is optional , It is not necessary to provide . Both of these functions accept Promise Object as a parameter .
then Method
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
Method returns a new one Promise example , So we can do the chain notation , namely 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 completed , Will return the result as a parameter , Pass in the second callback function .
catch Method
catch
The method is actually .then(null,rejection)
Another name for , Used to specify the callback function when an error occurs .
getJSON("/posts.json").then(function(posts) {
// ...
}).catch(function(error) {
// Handle getJSON and An error occurred while the previous callback function was running
console.log(' An error occurred !', error);
});
If Promise The state has become Resolved
, It's invalid to throw another error .
var promise = new Promise(function(resolve, reject) {
resolve('ok');
throw new Error('test');
});
promise
.then(function(value) {
console.log(value) })
.catch(function(error) {
console.log(error) });
// ok
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
Callback function for state ( namely then
Second parameter of ), Always used catch
Method .
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) {
//cb
// success
})
.catch(function(err) {
// error
});
In the above code , The second is better than the first , The reason is that the second way of writing can capture the front then
Error in method execution , It's also closer to synchronous writing (try/catch)
.
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 .
It should be noted that ,catch
Method returns a Promise object , So it can be called later then
Method .
var someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// The next line will report an error , because x No statement
resolve(x + 2);
});
};
someAsyncThing()
.catch(function(error) {
console.log('oh no', error);
})
.then(function() {
console.log('carry on');
});
// oh no [ReferenceError: x is not defined]
// carry on
all Method
all
Method is used to add more than one Promise example , Pack into a new one Promise example .
var 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 Instance of object , If not , I'll call the following Promise.resolve
Method , Convert parameter to Promise example , Further processing .
p The status of the p1、p2、p3 decision , There are two cases .
- Only p1、p2、p3 The state of
fulfilled
,p The state offulfilled
, here p1、p2、p3 The return value of consists of an array , Pass to p Callback function for .
- as long as p1、p2、p3 One of them was rejected
,p The state of rejected
, At this time, the first was reject The return value of the instance of , Will pass to p Callback function for .
race Method
race
Again, multiple Promise example , Pack into a new one Promise example
var 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.
var p = Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('request timeout')), 5000)
})
])
p.then(response => console.log(response))
p.catch(error => console.log(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 .
resolve Method
Sometimes you need to convert an existing object to Promise object ,resolve
Method plays this role .
resolve
It's equivalent to the following
Promise.resolve('foo')
// Equivalent to
new Promise(resolve => resolve('foo'))
reject Method
reject
Method will return a new Promise example , The state of the instance is rejected
. Its parameter usage and resolve
The method is exactly the same .
var p = Promise.reject(' Something went wrong ');
// Equate to
var p = new Promise((resolve, reject) => reject(' Something went wrong '))
p.then(null, function (s){
console.log(s)
});
// Something went wrong
done Method
Promise The callback chain of the object , No matter to then
Method or catch
Methods the ending , If the last method throws an error , May not be able to capture ( because Promise Internal errors do not bubble to the big picture ). therefore , We can provide one done
Method , Always at the end of the callback chain , Be sure to throw any possible errors .
asyncFunc()
.then(f1)
.catch(r1)
.then(f2)
.done();
Its implementation code is quite simple
Promise.prototype.done = function (onFulfilled, onRejected) {
this.then(onFulfilled, onRejected)
.catch(function (reason) {
// Throws a global error
setTimeout(() => {
throw reason }, 0);
});
};
As can be seen from the code above ,done
Use of methods , Can be like then
The method works like that , Provide Fulfilled
and Rejected
Callback function for state , You can also not provide any parameters . But anyway ,done
Will catch any possible errors , And throw to the global .
finally Method
finally
Method is used to specify whether Promise What is the final state of the object , Will perform the operation . It is associated with done
The biggest difference of methods , It takes a normal callback function as an argument , Regardless of status , This function must be executed anyway .
Here is an example , Server usage Promise Processing requests , And then use finally
Method turn off the server
server.listen(0)
.then(function () {
// run test
})
.finally(server.stop);
Its implementation is also very simple .
Promise.prototype.finally = function (callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => {
throw reason })
);
};
application : Loading pictures
We can load the image as a Promise, Once the load is complete ,Promise The state of is changing .
const preloadImage = function (path) {
return new Promise(function (resolve, reject) {
const image = new Image();
image.onload = resolve;
image.onerror = reject;
image.src = path;
});
};
Reference documents
边栏推荐
- Xctf--Web--Challenge--area Wp
- Online assignment of C language program design in the 22nd spring of Western Polytechnic University
- Unity obtains serial port data
- Unit asynchronous jump progress
- Expansion method of unity scanning circle
- How to prevent source code leakage in enterprises and institutions
- 【LeetCode】Easy | 225. Using queue to realize stack (pure C manual tearing queue)
- 旋转框目标检测mmrotate v0.3.1 学习配置
- Database SQL language 03 sorting and paging
- mmcv常用API介绍
猜你喜欢
Delete the repeating elements in the sorting list (simple questions)
Unity screenshot method
OpenCL线程代数库ViennaCL的使用
Super comprehensive summary | related improvement codes of orb-slam2 / orb-slam3!
Database SQL language 04 subquery and grouping function
86. 分隔链表
Introduction to mmcv common APIs
Learning about functions QAQ
[note] usage model tree of the unity resource tree structure virtualizingtreeview
Unity publishing /build settings
随机推荐
如何制作CSR(Certificate Signing Request)文件?
Very nervous. What should I do on the first day of software testing?
C语言基础小操作
Bev instance prediction based on monocular camera (iccv 2021)
uboot通过终端发送‘r‘字符读取ddr内存大小
企事业单位源代码防泄露工作该如何进行
Array pointers and pointer arrays
Wechat applet training 2
聲網,站在物聯網的“土壤”裏
/Path/to/ idiom, not a command
【LeetCode】Easy | 232. Using stack to realize queue (pure C manual tearing stack)
旋转框目标检测mmrotate v0.3.1 学习配置
Word frequency statistics (string, list)
Pyinstaller flash back
Unity determines whether the UI is clicked
【LeetCode】Easy | 225. Using queue to realize stack (pure C manual tearing queue)
东塔攻防世界—xss绕过安全狗
Installation and getting started with pytoch
The minecraft server address cannot be refreshed.
Remote sensing image /uda:curriculum style local to global adaptation for cross domain remote sensing image segmentation