当前位置:网站首页>Asynchronous learning
Asynchronous learning
2022-04-23 08:05:00 【Pen drawing Acacia】
(1)promise
1: Realization principle
It is mainly realized through callback function , The callback function is encapsulated inside , adopt then Method chain call , Show asynchronous code in the form of synchronization .
2:promise Characteristics
There are only three states : wait for , success , Failure
The state can only be changed once
3:promise The shortcomings of
Once executed, it cannot be cancelled , If an error occurs, it should be caught through the callback function
4:promis Constructor calls and promise The difference between chain calls
The call to the constructor is executed immediately
new Promise((resolve, reject) => {
console.log('new Promise')
resolve('success')
})
console.log('finifsh')
// new Promise -> finifsh
Promise Implementation of the chain call , That is to say, every call then After that, all the people who returned were Promise, And it's a brand new Promise, The reason is that the state is immutable . If you are in the then in Used return, that return The value of will be Promise.resolve()` packing
Promise.resolve(1)
.then(res => {
console.log(res) // => 1
return 2 // Package as Promise.resolve(2)
})
.then(res => {
console.log(res) // => 2
})
5:promise The implementation of the
function myPromise(excus)
{
let that=this;
// Record the current state
that.state="pending";
// The value of success
that.value=null;
// The reason for the failure
that.rean=null;
// The staging area is used to solve asynchronous tasks
that.resolvedCallbacks = [];
that.rejectedCallbacks = [];
// Change the state of success
function resovle(value)
{
if(that.state=='pending')
{
that.state="Resolve";
that.value=value;
that.resolvedCallbacks.forEach(item=>{
item(value);
})
}
}
// Change the state of failure
function reject(value)
{
if(that.state=='pending')
{
that.state='Reject';
that.rean=value;
that.rejectedCallbacks.forEach(item=>{
item(rean);
})
}
}
// Execute now
excus(resovle,reject);
}
//then
myPromise.prototype.then=function(resovle,reject){
// Resolve asynchronous calls
that=this;
resovle =typeof resovle ==='function'?resovle:function(data){
return data;
}
reject =typeof reject ==='function'?reject:function(err){
throw err;
}
if(that.state=='pending')
{
that.resolvedCallbacks.push(resovle);
that.rejectedCallbacks.push(reject);
}
return new myPromise((onfullfilled,Onreject)=>{
if(that.state==='Resolve')
{
try{
x=onfullfilled(that.value);
console.log(x);
resovle(x);
}catch(e){
reject(e);
}
}
})
}
var p=new myPromise((resovle,reject)=>{
setTimeout(() => {
resovle('123');
}, 1000);
});
p.then((result) => {
console.log(result);
},(err) => {
console.log(err);
});
//promise Implement asynchronous publisher subscription mode
6:promiseall The implementation of the
function promiseAll(Promises)
{
return new Promise(function(resolve,reject){
if(!Array.isArray(Promises))
{
return reject(new TypeError("argument"));
}
var countNum=0;
var promiseNum=Promises.length;
var resolvedvalue=new Array(promiseNum);
for(let i=0;i<promiseNum;i++)
{
Promise.resolve(Promises[i]).then(function(value){
countNum++;
resolvedvalue[i]=value;
if(countNum===promiseNum)
{
return resolve(resolvedvalue);
}
},function(reason){
return reject(reason);
})
}
})
}
var p1=Promise.resolve(1),
p2=Promise.resolve(2),
p3=Promise.resolve(3);
promiseAll([p1,p2,p3]).then(function(value){
console.log(value)
})
(2):async And await
1:async function
It will return one promise object , adopt promise.resolve() encapsulate
2:await and async Matching use of
advantage : and promise Compare , Processed then Chain call of , More concise
shortcoming : That is, without dependence , Will result in performance degradation . Use when there are no dependencies promise.all() More efficient .
await Implementation principle of :
Mainly promise The combination of grammar sugar and generator ,await Implemented through a generator , Save the information in the current stack , When executing asynchronous code, read the information in the stack and the returned promise Object combination
generator
When we instantiate a generator , Will return an iterator Iterator.
And then through yield/next Control the execution order of the code , When we execute yield The execution of code is suspended inside the generator function , The outside of the generator is still active , Internal resources are preserved , It's just a pause .
When we execute next When , The execution will start from the suspended position .
Why? next Than yield One more ?
Because when we instantiate the generator , The code is not executed immediately , To pass the next Start the generator , hinder yield and next Make a correspondence . therefore next than yield More than a .
版权声明
本文为[Pen drawing Acacia]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230624332886.html
边栏推荐
- 读书笔记
- 数据库之MySQL——基本常用查询命令
- Search and replacement of C text file (WinForm)
- 內網滲透系列:內網隧道之icmpsh
- 《内网安全攻防:渗透测试实战指南》读书笔记(八):权限维持分析及防御
- Série de pénétration Intranet: icmpsh du tunnel Intranet
- Redis -- why is the string length of string emstr the upper limit of 44 bytes?
- CTF-MISC学习之从开始到放弃
- MySQL——第一章节(MySQL中的数据类型)
- SAP GUI security
猜你喜欢

Dvwa 靶场练习记录

国基北盛-openstack-容器云-环境搭建

【编程实践/嵌入式比赛】嵌入式比赛学习记录(一):TCP服务器和web界面的建立

C problem of marking the position of polygons surrounded by multiple rectangles

TA notes of Zhuang understand (VII) < Lambert + Phong + shadow + 3evcolor + Ao >

《内网安全攻防:渗透测试实战指南》读书笔记(五):域内横向移动分析及防御

nacos源码分析思路

The displayed amount of ABAP ALV is inconsistent with the exported amount

LeetCode 1611. 使整数变为 0 的最少操作次数

Intranet penetration series: pingtunnel of Intranet tunnel
随机推荐
Reptile learning notes, learning reptile, read this article is enough
Learning records of some shooting ranges: sqli labs, upload labs, XSS
求3个字符串(每串不超过20个字符)中的最大者。
Redis transaction implements optimistic locking principle
云计算赛项--2020年赛题基础部分[任务3]
yum源仓库本地搭建的两种方法
Talking about distributed storage from ES, mongodb, redis and rocketmq
Intranet penetration series: icmptunnel of Intranet tunnel (Master James Barlow's)
Three minutes to teach you to use Houdini fluid > > to solve particle fluid droplets
How does Apache Hudi accelerate traditional batch mode?
vivo,硬件安全的爱与雷霆
读书笔记
CSV Column Extract列提取
Buctf MISC brossage
Internal network security attack and defense: a practical guide to penetration testing (VII): cross domain attack analysis and defense
MySQL -- the secret of lock -- how to lock data
Intranet penetration series: ICMP of Intranet tunnel_ Tran
Zhuang understand's TA notes (VI) < fakeenvreflect & rust, rust effect >
Dvwa 靶场练习记录
《内网安全攻防:渗透测试实战指南》读书笔记(四):权限提升分析及防御