当前位置:网站首页>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 .
边栏推荐
- 明明设计的是高带宽,差点加工成开路?
- Matlab [function derivation]
- V79.01 Hongmeng kernel source code analysis (user mode locking) | how to use the fast lock futex (Part 1) | hundreds of blogs analyze the openharmony source code
- NIO-零拷贝
- 固定资产管理系统让企业动态掌握资产情况
- Shell脚本-case in 和正则表达式
- Shell脚本-for循环和for int循环
- [MFC development (17)] advanced list control list control
- [MFC development (16)] tree control
- C language student information management system
猜你喜欢

Memory size end

TV size and viewing distance

Bimianhongfu queren()

Guidelines and principles of did

猿人学第20题(题目会不定时更新)

电脑小技巧

3、Modbus通讯协议详解

Centos7 shell脚本一键安装jdk、mongo、kafka、ftp、postgresql、postgis、pgrouting

Principle and application of single chip microcomputer - principle of parallel IO port

ARM v7的体系结构A、R、M区别,分别应用在什么领域?
随机推荐
个人装修笔记
Differences among tasks, threads and processes
猿人学第20题(题目会不定时更新)
DataBinding源码分析
Shell脚本-while循环详解
Performance improvement 2-3 times! The second generation Kunlun core server of Baidu AI Cloud was launched
你了解数据是如何存储的吗?(C整型和浮点型两类)
基础:3.opencv快速入门图像和视频
基础:2.图像的本质
Matlab tips (23) matrix analysis -- simulated annealing
明明设计的是高带宽,差点加工成开路?
避免按钮重复点击的小工具bimianchongfu.queren()
安装Oracle EE
R语言观察日志(part24)--初始化设置
What are the differences between the architecture a, R and m of arm V7, and in which fields are they applied?
C language student information management system
Brief introduction to AES
公网集群对讲+GPS可视追踪|助力物流行业智能化管理调度
Shell脚本-变量的定义、赋值和删除
Introduction to 18mnmo4-5 steel plate executive standard and delivery status of 18mnmo4-5 steel plate, European standard steel plate 18mnmo4-5 fixed rolling