当前位置:网站首页>Promise asynchronous programming
Promise asynchronous programming
2022-07-01 08:52:00 【Deep sea blue mountains】
Catalog
One 、 The callback function itself is synchronous code
3、 ... and 、Promise Precautions for
Four 、Promise frequently-used Api
One 、 Callback function
The callback function itself is synchronous code
Usually writing JavaScript Code , Most of the callbacks used are nested in the form of asynchronous functions , Therefore, some developers think that all callback functions are asynchronous processes . It's not like this , The real explanation is :JavaScript Callback function structure in , The default is synchronous structure , because JavaScript Rules for the single threaded asynchronous model , If you want to write asynchronous code , You must use callback nesting to achieve , So the callback function structure is not necessarily asynchronous code , But asynchronous code must be a callback function structure .
Two 、Promise Introduce
Be careful :Promise It's the synchronization method ,promise.then It's an asynchronous method
console.log('-- Start ----');
const p = new Promise(function(resolve, reject) {
console.log(' call Promise');
// resolve Can trigger then Callback execution in
resolve(' Yes resolve');
// reject(' Abnormal ');
});
p.then(res => {
console.log('then perform ', res);
})
.catch(err => {
console.log('catch perform ', err);
})
.finally(() => {
console.log('finally perform ');
});
console.log('-- end ----');
Execution results :
-- Start ----
call Promise
-- end ----
then perform Yes resolve
finally perform Through the example above , We can know new Promise The callback function in is indeed executed in the synchronization task , The second is if the callback function does not execute internally resolve perhaps reject that p There will be no output inside the callback function behind the object , And running resolve After the function .then and .finally Will execute , It's running reject after ,catch and finally Will execute
1. Promise structure
every last Promise Objects contain three parts
- [[Prototype]]: representative Promise Prototype object
- [[PromiseState]]: representative Promise The current state of the object
- [[PromiseResult]]: representative Promise The value of the object , They correspond to each other resolve or reject Incoming results
2. Promise Three states of :
- pending: The initial state , Also called ready state , This is Promise The initial state of an object definition , At this time Promise Just initialize and register all the tasks on his object .
- fulfilled: Completed , It usually represents the successful execution of a task , When initializing resolve Execution time ,Promise The status of is changed to fulfilled, also then The callback function registered by the function will start to execute ,resolve The parameters passed in will enter the callback function as formal parameters .
- rejected: Rejected , Usually represents a failed task , Or the process is interrupted , When calling reject Function time ,catch The registered callback function will trigger , also reject The contents passed in will become the formal parameters of the callback function .
3. Promise Chain call of
The essence of chain call is to call the end of these functions that support chain call , It returns an object containing itself or a new self , These methods can realize chain call .
// call chaining
function MyPromise() {
return this;
}
MyPromise.prototype.then = function() {
console.log(' Triggered then');
return this;
};
new MyPromise().then().then();3、 ... and 、Promise Precautions for
1. call chaining
// Precautions for chained calls
let pr = new Promise((resolve, reject) => {
resolve('promise example ');
});
pr.then(res => {
console.log('res'); // undefined
return '123';
})
.then(res => {
console.log('res'); // 123
return new Promise(resolve => {
resolve(456);
});
})
.then(res => {
console.log('res'); // 456
return ' Directly returned results ';
})
.then()
.then(' character string ')
.then(res => {
console.log('res'); // Directly returned results
});
1、 As long as there is then() And triggered resolve, The whole chain will run to the end , The parameters of the first callback function in this process are resolve Incoming value
2、 Each subsequent function can use retrun Return a result , If no result is returned , next then The parameter of the callback function in is undefined
3、 If the return result is a normal variable , Then this value is a then Parameters of the callback function in the
4、 If you return a Promise object , So this Promise object resolve The result will be the next time then The parameters of the callback function in 【 Directly understood as , return Promise Object time , next then It's the object then】
5、 If then What is passed in is not a function or no value ,Promise The chain does not break then Chain call of , And the last return result before that , Will go directly to the nearest right then Callback function in as a parameter
2. Promise interrupt
There are two forms [throw/reject] It can make then The chain of is broken , If the interrupt is triggered again catch Implementation .
// Interrupt of chain call
let pe = new Promise((resolve, reject) => {
resolve('Promise Value ');
});
pe.then(res => {
console.log(res);
})
.then(res => {
// Two ways to interrupt Promise
// throw ' adopt throw interrupt ';
return Promise.reject('reject interrupt ');
})
.then(res => {
console.log(res);
}).catch(res => {
console.log('catch perform ', res);
});;Four 、Promise frequently-used Api
1. Promise.all()
When we need to use asynchronous process control in our code , Can pass Promise.then To enable asynchronous processes to execute one by one , Suppose there are three interfaces , And ensure that all the data of the three interfaces are returned , To render the page . If a Time consuming 1s、b Time consuming 0.8s、c The interface takes 1.4s, If you use Promise.then To perform process control , If you pass then Asynchronous control of functions , You must wait for each interface to be called before calling the next , The total time it takes is 1+0.8+1.4=3.2s. This accumulation obviously increases the time consumption of interface calls , therefore Promise Provides a all To solve this problem :
Promise.all([promise object ,promise object ,...]).then( Callback function )
The parameter of the callback function is an array , According to the first parameter promise The order of objects shows each promise Return result of .
With the help of Promise.all To achieve , Wait until the slowest interface returns data , Get the data of all interfaces together , Then the time consumption will only be based on the time consumption of the slowest interface 1.4s perform , Total savings 1.8s.
Promilse.all It is equivalent to unified processing of multiple promise Mission , Ensure that all of these promise The state of the object changes to fulfilled And then it triggers all Of .then Function to ensure that the all The results of all tasks in return
2.Promise.race()
Promise.race([promise object ,promise object ,...]).then( Callback function )
The parameter of the callback function is the fastest one in the previous array promise The return value of .
Promilse.race() It is equivalent to competing all the incoming tasks , They are the first to change their state into fulfilled The task will be triggered directly race Of .then Function and return its value , Mainly used when competing among multiple tasks
5、 ... and 、Async and Await
async and await It is equivalent to using the built-in execution function Generator function , therefore async and await It has gradually become the ultimate solution for mainstream asynchronous process control .
async handleTest() {
console.log('1');
// this.test();// await Method
this.promisTest(); // Equivalent promise Method
console.log('2');
// Output order :1,3,2,4
},
// await Method
async test() {
console.log(3);
var a = await 4;
console.log(a);
},
// This method is test Methodical promsise How to write it
promisTest() {
new Promise(resolve => {
console.log(3);
resolve(4);
}).then(res => {
console.log(res);
});
}async There is one of the biggest features of the function , It's the first one await Will exist as a watershed , At the first await And the code above , All are synchronized code regions equivalent to new Promise The callback , first await And the following code , It becomes an asynchronous code region equivalent to then The callback .
边栏推荐
- It is designed with high bandwidth, which is almost processed into an open circuit?
- factory type_ Id:: create process resolution
- Matlab tips (23) matrix analysis -- simulated annealing
- Foundation: 2 The essence of image
- 避免按钮重复点击的小工具bimianchongfu.queren()
- 基础:3.opencv快速入门图像和视频
- Matlab [functions and images]
- The meaning of yolov5 training visualization index
- 3. Detailed explanation of Modbus communication protocol
- yolov5训练可视化指标的含义
猜你喜欢

Share 7 books I read in the first half of 2022

钓鱼识别app

安装Oracle EE

Glitch free clock switching technology

Pain points and solutions of equipment management in large factories

动态代理

3、Modbus通讯协议详解

Nacos - 配置管理

What is the material of 16mo3 steel plate? What is the difference between 16mo3 and Q345R?

Embedded Engineer Interview Question 3 Hardware
随机推荐
挖财打新股安全吗
Matlab [function derivation]
NIO-零拷贝
嵌入式工程师面试-常问问题集
jeecg 重启报40001
How to manage fixed assets well? Easy to point and move to provide intelligent solutions
C语言指针的进阶(上篇)
AVL树的理解和实现
内存大小端
如何解决固定资产管理和盘点的难题?
Shell脚本-case in 和正则表达式
Shell脚本-if else语句
win7 pyinstaller打包exe 后报错 DLL load failed while importing _socket:参数错误
中小企业固定资产管理办法哪种好?
个人装修笔记
安装Oracle EE
Principle and application of single chip microcomputer - principle of parallel IO port
Jetson Nano 安装TensorFlow GPU及问题解决
C language student information management system
1. Connection between Jetson and camera