当前位置:网站首页>async原理实现
async原理实现
2022-06-29 12:10:00 【Henry_楠】
前言
如果不了解使用的可参考 async 函数,这里不再赘述。
想要看原理的童鞋,需要了解下 Generator函数
原理
async实现就是将 Generator 函数和自动执行器,包装在一个函数里。
async function fn(args) {
// ...
}
function fn(args) {
return spawn(function* () {
// ...
})
}
所有的 async 函数都可以写成上面的第二种形式,其中 spawn 函数就是自动执行器。
function spawn(genF) {
return new Promise(function(resolve, reject) {
const gen = genF();
function step(nextF) {
let next;
try {
next = nextF();
} catch(e) {
return reject(e);
}
if(next.done) {
return resolve(next.value);
}
Promise.resolve(next.value).then(function(v) {
step(function() {
return gen.next(v); });
}, function(e) {
step(function() {
return gen.throw(e); });
});
}
step(function() {
return gen.next(undefined); });
});
}
常见面试题
- 实现一个sleep
- 实现一个红绿灯: 红灯2秒,黄灯1秒,绿灯3秒
- 使用 async 实现 Promise.all()的效果
实现一个 sleep: 每隔1秒输出 1, 2, 3, 4, 5
function sleep(interval) {
return new Promise(resolve => {
setTimeout(resolve, interval);
})
}
// 用法
async function one2FiveInAsync() {
for (let i = 1; i <= 5; i++) {
console.log(i);
await sleep(1000);
}
}
one2FiveInAsync();
实现一个红绿灯: 红灯2秒,黄灯1秒,绿灯3秒
function sleep(duration) {
return new Promise(resolve => {
setTimeout(resolve, duration);
})
}
async function changeColor(color, duration) {
console.log('当前颜色', color);
await sleep(duration);
}
async function main() {
await changeColor('红色', 2000);
await changeColor('黄色', 1000);
await changeColor('绿色', 3000);
}
main();
使用 async 实现 Promise.all()的效果
async function test() {
const getFoo = (i) => {
return new Promise(resolve => setTimeout(() => {
resolve(i)
}, 1000))
}
// 写法一
// let values = await Promise.all([getFoo(1), getFoo(2), getFoo(3), getFoo(4)]);
// 写法二
const f1 = getFoo(1)
const f2 = getFoo(2)
const f3 = getFoo(3)
const f4 = getFoo(4)
let values = [await f1, await f2, await f3, await f4]
console.log('values', values)
}
test()
边栏推荐
- QQ group was stolen, a large-scale social death scene caught off guard
- Interview shock 61: tell me about MySQL transaction isolation level?
- MATLAB求极限
- Gbase8s database select has order by Clause 3
- MIT linear algebra Chinese Notes
- InDesign plug-in - general function development -js debugger open and close -js script development -id plug-in
- Lm07 - detailed discussion on cross section strategy of futures
- C#通過中序遍曆對二叉樹進行線索化
- Adjacency matrix and adjacency table structure of C # realization graph
- Gbase8s database select has order by Clause 4
猜你喜欢

Cache consistency, delete cache, write cache, cache breakdown, cache penetration, cache avalanche

Proteus Software beginner notes

如何计算win/tai/loss in paired t-test

Unexpected ‘debugger‘ statement no-debugger

Blurred pictures become clear, one button two-color pictures, quickly organize local pictures These 8 online picture tools apply to join your favorites!

Bison uses error loop records

推荐模型复现(四):多任务模型ESMM、MMOE

C#通过中序遍历对二叉树进行线索化

Interview shock 61: tell me about MySQL transaction isolation level?

中职网络安全技能竞赛之应用服务漏洞扫描与利用(SSH私钥泄露)
随机推荐
InDesign plug-in - general function development -js debugger open and close -js script development -id plug-in
C#实现堆栈结构的定义、入栈、出栈
Cache consistency, delete cache, write cache, cache breakdown, cache penetration, cache avalanche
AGCO AI frontier promotion (6.29)
C # indexe l'arbre binaire en traversant l'ordre moyen
Cocos star meetings at Hangzhou station in 2022
C # realizes the first order traversal, middle order traversal and second order traversal of binary tree
Interpolated scatter data
Recommended model recurrence (I): familiar with torch rechub framework and use
Gbase8s database select has order by Clause 4
Comment calculer Win / Tai / Loss in paired t - test
NvtBack
Qt的信号与槽
[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial
超 Nice 的表格响应式布局小技巧
Inferiority complex and transcendence the meaning of life to you
Adjacency matrix and adjacency table structure of C # realization graph
How to create new user for ORACLE 19c (CDB & PDB)
Gbase8s database select has order by Clause 5
C#通过中序遍历对二叉树进行线索化