当前位置:网站首页>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
边栏推荐
- Codeforces Round #753 (Div. 3)
- [free setup] asp Net online course selection system design and Implementation (source code +lunwen)
- C语言读取BMP文件
- Neo4j installation tutorial
- 天梯赛练习集题解LV1(all)
- Dotnet replaces asp Net core's underlying communication is the IPC Library of named pipes
- Base de données Advanced Learning Notes - - SQL statements
- [recommended by bloggers] C WinForm regularly sends email (with source code)
- 02-项目实战之后台员工信息管理
- Case analysis of data inconsistency caused by Pt OSC table change
猜你喜欢
![[recommended by bloggers] asp Net WebService background data API JSON (with source code)](/img/04/c721e6177b578b30cbbf334cb1b6c9.png)
[recommended by bloggers] asp Net WebService background data API JSON (with source code)

Image recognition - pyteseract TesseractNotFoundError: tesseract is not installed or it‘s not in your path

引入了junit为什么还是用不了@Test注解

保姆级出题教程

MySQL主從複制、讀寫分離

UDS learning notes on fault codes (0x19 and 0x14 services)

Detailed reading of stereo r-cnn paper -- Experiment: detailed explanation and result analysis
![[free setup] asp Net online course selection system design and Implementation (source code +lunwen)](/img/ac/b518796a92d00615cd374c0c835f38.jpg)
[free setup] asp Net online course selection system design and Implementation (source code +lunwen)

Did you forget to register or load this tag 报错解决方法

QT creator specifies dependencies
随机推荐
Software I2C based on Hal Library
解决安装Failed building wheel for pillow
JDBC原理
Software testing and quality learning notes 3 -- white box testing
Install mysql5.5 and mysql8.0 under windows at the same time
neo4j安装教程
Django运行报错:Error loading MySQLdb module解决方法
MySQL other hosts cannot connect to the local database
01 project demand analysis (ordering system)
AcWing 1294. Cherry Blossom explanation
Basic use of redis
Unable to call numpy in pycharm, with an error modulenotfounderror: no module named 'numpy‘
Pytorch基础
ES6 let 和 const 命令
SSM integrated notes easy to understand version
软件测试-面试题分享
Ansible实战系列二 _ Playbook入门
Picture coloring project - deoldify
机器学习--人口普查数据分析
Punctual atom stm32f103zet6 download serial port pin