当前位置:网站首页>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
边栏推荐
- strcat()、strcpy()、strcmp()、strlen()
- Go语学习笔记 - 数组 | 从零开始Go语言
- Internal network security attack and defense: a practical guide to penetration testing (IV): Authority improvement analysis and defense
- 《内网安全攻防:渗透测试实战指南》读书笔记(八):权限维持分析及防御
- Research on system and software security (4)
- 从ES、MongoDB、Redis、RocketMQ出发谈分布式存储
- Research on system and software security (2)
- Guoji Beisheng openstack container cloud environment construction
- 使用 Ingress 实现金丝雀发布
- 云计算赛项--2020年赛题基础部分[任务3]
猜你喜欢
随机推荐
CSV Column Extract列提取
KCD_ EXCEL_ OLE_ TO_ INT_ Convert reports an error sy subrc = 2
【编程实践/嵌入式比赛】嵌入式比赛学习记录(一):TCP服务器和web界面的建立
爬虫学习笔记,学习爬虫,看本篇就够了
云计算赛项--2020年赛题基础部分[任务3]
Internal network security attack and defense: a practical guide to penetration testing (8): Authority maintenance analysis and defense
C smoothprogressbar custom progress bar control
Principle of sentinel integrating Nacos to update data dynamically
[programming practice / embedded competition] learning record of embedded competition (II): picture streaming based on TCP
Feign source code analysis
When using flash, the code ends automatically without an error, the connection cannot be maintained, and the URL cannot be accessed.
Analysis of Nacos source code
求3个字符串(每串不超过20个字符)中的最大者。
yum源仓库本地搭建的两种方法
Série de pénétration Intranet: icmpsh du tunnel Intranet
Cloud computing skills competition -- Part 2 of openstack private cloud environment
SAP tr manual import system operation manual
云计算技能大赛 -- openstack私有云环境 第二部分
MySQL -- the secret of lock -- how to lock data
How does feign integrate hystrix








![[极客大挑战 2019]Havefun1](/img/8b/b15bf31771d54db25f24d630e64093.png)