当前位置:网站首页>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
边栏推荐
- Learning question 1:127.0.0.1 refused our visit
- JDBC原理
- [number theory] divisor
- Kept VRRP script, preemptive delay, VIP unicast details
- Django running error: error loading mysqldb module solution
- Machine learning notes week02 convolutional neural network
- Deoldify project problem - omp:error 15:initializing libiomp5md dll,but found libiomp5md. dll already initialized.
- Ubuntu 20.04 安装 MySQL
- Rhcsa certification exam exercise (configured on the first host)
- Install mongdb tutorial and redis tutorial under Windows
猜你喜欢

Introduction and use of automatic machine learning framework (flaml, H2O)

图片上色项目 —— Deoldify

QT creator runs the Valgrind tool on external applications

Knowledge Q & A based on Apache Jena

Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
![[number theory] divisor](/img/ec/036d7e76cc566c08d336444f2898e1.jpg)
[number theory] divisor

Swagger, Yapi interface management service_ SE

图像识别问题 — pytesseract.TesseractNotFoundError: tesseract is not installed or it‘s not in your path

Picture coloring project - deoldify

连接MySQL数据库出现错误:2059 - authentication plugin ‘caching_sha2_password‘的解决方法
随机推荐
Ansible实战系列三 _ task常用命令
Ansible practical series I_ introduction
Did you forget to register or load this tag
MySQL other hosts cannot connect to the local database
數據庫高級學習筆記--SQL語句
保姆级出题教程
[number theory] divisor
Antlr4 uses keywords as identifiers
报错解决 —— io.UnsupportedOperation: can‘t do nonzero end-relative seeks
天梯赛练习集题解LV1(all)
Ansible实战系列一 _ 入门
自动机器学习框架介绍与使用(flaml、h2o)
[recommended by bloggers] C # generate a good-looking QR code (with source code)
double转int精度丢失问题
ES6 Promise 对象
Django运行报错:Error loading MySQLdb module解决方法
What does BSP mean
ES6 let 和 const 命令
Heating data in data lake?
Django running error: error loading mysqldb module solution