当前位置:网站首页>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
边栏推荐
- 解决安装Failed building wheel for pillow
- PyCharm中无法调用numpy,报错ModuleNotFoundError: No module named ‘numpy‘
- 图片上色项目 —— Deoldify
- Copie maître - esclave MySQL, séparation lecture - écriture
- PHP - whether the setting error displays -php xxx When PHP executes, there is no code exception prompt
- QT creator custom build process
- Data dictionary in C #
- JDBC原理
- ES6 let 和 const 命令
- vs2019 第一个MFC应用程序
猜你喜欢
Install mongdb tutorial and redis tutorial under Windows
Introduction and use of automatic machine learning framework (flaml, H2O)
[recommended by bloggers] C # generate a good-looking QR code (with source code)
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
AcWing 1298. Solution to Cao Chong's pig raising problem
AcWing 242. A simple integer problem (tree array + difference)
[free setup] asp Net online course selection system design and Implementation (source code +lunwen)
Classes in C #
How to configure flymcu (STM32 serial port download software) is shown in super detail
Use dapr to shorten software development cycle and improve production efficiency
随机推荐
How to set up voice recognition on the computer with shortcut keys
Leetcode 461 Hamming distance
Summary of numpy installation problems
vs2019 第一个MFC应用程序
Number game
安装numpy问题总结
Dotnet replaces asp Net core's underlying communication is the IPC Library of named pipes
[蓝桥杯2017初赛]包子凑数
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
Django running error: error loading mysqldb module solution
PHP - whether the setting error displays -php xxx When PHP executes, there is no code exception prompt
Ansible实战系列二 _ Playbook入门
MySQL主從複制、讀寫分離
neo4j安装教程
QT creator create button
Julia 1.6 1.7 common problem solving
Swagger, Yapi interface management service_ SE
机器学习--人口普查数据分析
Machine learning -- census data analysis
AcWing 1298.曹冲养猪 题解