当前位置:网站首页>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()
边栏推荐
- Interview shock 61: tell me about MySQL transaction isolation level?
- Interview shock 61: tell me about MySQL transaction isolation level?
- oracle 19c : change the user sys/system username pasword under Linux
- Introduction to multi project development - business scenario Association basic introduction test payroll
- C # implementation of binary tree non recursive middle order traversal program
- 倍福TwinCAT3 的OPC_UA通信测试案例
- C#实现二叉树的层次遍历
- Gbase8s database into standard and into raw clauses
- Gbase8s database for read only clause
- 2022.6.28-----leetcode. three hundred and twenty-four
猜你喜欢

Quick look | the long-awaited 2022 Guangzhou assistant testing engineer's real problem analysis is finally released

How to calculate win/tai/loss in paired t-test

How to install oracle19c in Centos8
![[cloud native] 2.4 kubernetes core practice (middle)](/img/1e/b1b22caa03d499387e1a47a5f86f25.png)
[cloud native] 2.4 kubernetes core practice (middle)

倍福控制器连接松下EtherCAT伺服注意事项

C binary tree structure definition and node value addition

Can software related inventions be patented in India?

Earth observation satellite data

Go Senior Engineer required course | I sincerely suggest you listen to it. Don't miss it~

QT custom control: value range
随机推荐
超 Nice 的表格响应式布局小技巧
倍福TwinCAT3 的OPC_UA通信测试案例
Recommended model recurrence (I): familiar with torch rechub framework and use
Paper reproduction - ac-fpn:attention-guided context feature pyramid network for object detection
Pygame 精准检测图像碰撞
Go learning - build a development environment vscode development environment golang
在印度与软件相关的发明可不可以申请专利?
Problem solving: modulenotfounderror: no module named 'pip‘
[leetcode] 14. Longest public prefix
Cache consistency, delete cache, write cache, cache breakdown, cache penetration, cache avalanche
C # realize the definition, stack entry and stack exit of stack structure
MFC dialog program core -isdialogmessage function -msg message structure -getmessage function -dispatchmessage function
Murphy safety was selected for signing 24 key projects of Zhongguancun Science City
Cereal mall project
nvtmpp
Quick look | the long-awaited 2022 Guangzhou assistant testing engineer's real problem analysis is finally released
Interview shock 61: tell me about MySQL transaction isolation level?
MIT linear algebra Chinese Notes
安装typescript环境并开启VSCode自动监视编译ts文件为js文件
C#实现堆栈结构的定义、入栈、出栈