当前位置:网站首页>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
边栏推荐
猜你喜欢
Learn winpwn (3) -- sEH from scratch
Image recognition - pyteseract TesseractNotFoundError: tesseract is not installed or it‘s not in your path
Copie maître - esclave MySQL, séparation lecture - écriture
Redis的基础使用
QT creator runs the Valgrind tool on external applications
Detailed reading of stereo r-cnn paper -- Experiment: detailed explanation and result analysis
[recommended by bloggers] C # generate a good-looking QR code (with source code)
CSDN markdown editor
保姆级出题教程
One click extraction of tables in PDF
随机推荐
FRP intranet penetration
MySQL主從複制、讀寫分離
QT creator runs the Valgrind tool on external applications
Ansible实战系列二 _ Playbook入门
[recommended by bloggers] asp Net WebService background data API JSON (with source code)
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
How to build a new project for keil5mdk (with super detailed drawings)
QT creator specifies dependencies
Introduction to the easy copy module
打开浏览器的同时会在主页外同时打开芒果TV,抖音等网站
Armv8-a programming guide MMU (2)
[蓝桥杯2021初赛] 砝码称重
AI benchmark V5 ranking
JDBC原理
When you open the browser, you will also open mango TV, Tiktok and other websites outside the home page
SSM integrated notes easy to understand version
What does BSP mean
Software I2C based on Hal Library
MySQL completely uninstalled (windows, MAC, Linux)
TCP/IP协议(UDP)