当前位置:网站首页>ES6 promise object
ES6 promise object
2022-07-06 11:24:00 【imxlw00】
Promise Is a solution to asynchronous programming :
Promise It's an object , Through it, we can get the message of asynchronous operation ;
promise There are three states :pending( Waiting state ),fulfilled( Success state ),rejected( Failure state );
Once the status changes , It won't change .
create promise After the instance , It will execute immediately .**
Basic usage
const promise = new Promise(function (resolve, reject) {
let p = {
code: 200,
data: {
name: " Zhang San ",
age: 20,
sex: ' male '
}
};
setTimeout(function () {
if (p.code == 200) {
resolve(p.data);
} else {
reject("err");
}
}, 2000);
});
promise.then(function (value) {
console.log("sucess name=" + value.name);
}, function (error) {
console.log("error==" + error);
});
console.log("123");
Promise State and value of
Promise Objects have three states
- Pending( The initial state , It's not a state of success or failure .)
- Fulfilled( Have succeeded )
- Rejected( Failed )
The state can only be determined by Pending Turn into Fulfilled Or by the Pending Turn into Rejected , And the state will not change after it changes , It's going to stay that way .
Promise establish
var promise = new Promise(function(resolve, reject) {
// Asynchronous processing
// After processing 、 call resolve or reject
});
Promise The constructor takes a function as an argument , The two parameters of this function are resolve and reject.
resolve The delta function is going to be , take Promise Object state from Untreated become Handle a successful (unresolved => resolved), Called when the asynchronous operation succeeds , The result of the asynchronous operation is passed as a parameter .
reject The delta function is going to be , take Promise Object state from Untreated become Processing failed (unresolved => 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 and catch Methods specify resolved State and rejected Callback function for state .
then Method
var p = new Promise(function(resolve, reject){
// When the asynchronous code executes successfully , We will call resolve(...), Called when asynchronous code fails reject(...)
// In this case , We use setTimeout(...) To simulate asynchronous code , The actual encoding might be XHR Request or request HTML5 Some of API Method .
setTimeout(function(){
resolve(" success !"); // Code execution is normal !
}, 250);
});
p.then(function(successMessage){
//successMessage The value of is called above resolve(...) Method .
//successMessage Parameters don't have to be string types , Here's just an example
document.write("Yay! " + successMessage);
});
For the instantiated promise Object can call promise.then() Method , Pass on resolve and reject Method as callback .
promise.then() yes promise The most commonly used method .
catch usage
catch The execution is and reject Same , That is to say if Promise The state of becomes reject when , Will be catch Catch .
If... Is set before reject Callback function for method , be catch You won't catch the state changing to reject The situation of .
If in resolve perhaps reject When something goes wrong , Will be catch Catch .
promise.then(onFulfilled).catch(onRejected)
catch(err=>{}) Method is equivalent to then(null,err=>{})
all() Method
all() Methods provide the ability to perform asynchronous operations in parallel , And the callback is executed after all asynchronous operations are executed .
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 .(Promise.all Method arguments are not necessarily arrays , But it must have iterator Interface , And every member returned is Promise 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 reject The return value of the instance of , Will pass to p Callback function for .
let meInfoPro = new Promise( (resolve, reject)=> {
setTimeout(resolve, 500, 'P1');
});
let youInfoPro = new Promise( (resolve, reject)=> {
setTimeout(resolve, 600, 'P2');
});
// At the same time p1 and p2, And when they're all done then:
Promise.all([meInfoPro, youInfoPro]).then( (results)=> {
console.log(results); // To obtain a Array: ['P1', 'P2']
});
race
stay all Callback function in , Wait until all Promise It's all done , Then execute the callback function ,race It will not wait until the first Promise Change the state and start executing the callback function .
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 The return value of .
let meInfoPro1 = new Promise( (resolve, reject)=> {
setTimeout(resolve, 500, 'P1');
});
let meInfoPro2 = new Promise( (resolve, reject)=> {
setTimeout(resolve, 600, 'P2');
});
Promise.race([meInfoPro1, meInfoPro2]).then((result)=> {
console.log(result); // P1
});
When we request a picture resource , It will take too long , Give feedback to users
use race Set timeout for an asynchronous request , And execute corresponding operation after timeout
function requestImg(imgSrc) {
return new Promise((resolve, reject) => {
var img = new Image();
img.onload = function () {
resolve(img);
}
img.src = imgSrc;
});
}
// The time delay function , Used to time requests
function timeout() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(' Picture request timeout ');
}, 5000);
});
}
Promise.race([requestImg('images/2.png'), timeout()]).then((data) => {
console.log(data);
}).catch((err) => {
console.log(err);
});
resolve Method 、reject Method
resolve() Method to convert an existing object to Promise object , The state of the instance is fulfilled
reject() Method returns a new one Promise example , The state of the instance is rejected
let p = Promise.resolve('foo');
// Equivalent to new Promise(resolve=>resolve('foo'));
p.then((val)=>{
console.log(val);
})
let p2 = Promise.reject(new Error(' Something went wrong '));
// Equivalent to let p2 = new Promise((resolve,reject)=>reject(new Error(' Something went wrong )));
p2.catch(err => {
console.log(err);
})
The above code generates a new Promise Instance of object p, Its state is fulfilled, So the callback function will execute immediately ,Promise.resolve The parameter of the method is the parameter of the callback function .
If Promise.resolve The parameter of the method is a Promise Instance of object , Will be returned intact .
Promise.reject(reason) Method also returns a new Promise example , The state of the instance is rejected.Promise.reject Method parameters reason, Will be passed to the instance's callback function .
Reference link :
https://blog.csdn.net/u013967628/article/details/86569262
https://www.runoob.com/w3cnote/javascript-promise-object.html
https://juejin.cn/post/6844903470823145486
https://www.cnblogs.com/ming1025/p/13092502.html
边栏推荐
- AcWing 179.阶乘分解 题解
- Error reporting solution - io UnsupportedOperation: can‘t do nonzero end-relative seeks
- Are you monitored by the company for sending resumes and logging in to job search websites? Deeply convinced that the product of "behavior awareness system ba" has not been retrieved on the official w
- Principes JDBC
- ES6 Promise 对象
- AcWing 1298.曹冲养猪 题解
- When you open the browser, you will also open mango TV, Tiktok and other websites outside the home page
- Ansible实战系列三 _ task常用命令
- QT creator test
- Learn winpwn (3) -- sEH from scratch
猜你喜欢
Rhcsa certification exam exercise (configured on the first host)
Picture coloring project - deoldify
Cookie setting three-day secret free login (run tutorial)
AI benchmark V5 ranking
Machine learning -- census data analysis
解决安装Failed building wheel for pillow
One click extraction of tables in PDF
Software testing and quality learning notes 3 -- white box testing
Introduction and use of automatic machine learning framework (flaml, H2O)
Software I2C based on Hal Library
随机推荐
Did you forget to register or load this tag
机器学习笔记-Week02-卷积神经网络
When you open the browser, you will also open mango TV, Tiktok and other websites outside the home page
[recommended by bloggers] background management system of SSM framework (with source code)
Swagger, Yapi interface management service_ SE
AI benchmark V5 ranking
Windows下安装MongDB教程、Redis教程
The virtual machine Ping is connected to the host, and the host Ping is not connected to the virtual machine
MySQL与c语言连接(vs2019版)
L2-001 紧急救援 (25 分)
解决安装Failed building wheel for pillow
LeetCode #461 汉明距离
连接MySQL数据库出现错误:2059 - authentication plugin ‘caching_sha2_password‘的解决方法
Image recognition - pyteseract TesseractNotFoundError: tesseract is not installed or it‘s not in your path
error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_s instead
PHP - whether the setting error displays -php xxx When PHP executes, there is no code exception prompt
Install mysql5.5 and mysql8.0 under windows at the same time
QT creator specifies dependencies
Attention apply personal understanding to images
软件测试-面试题分享