知食记
搜索文档…
模拟实现async
async是基于generator的
真实使用
1
async function fn(args) { ... }
2
3
// 可以以下来模拟
4
const asyncFn = wrap(fn)
5
asyncFn(args)
Copied!
简版实现
1
const wrap = (genFn) =>{
2
return (...args) => new Promise((resolve, reject) => {
3
const g = genFn(...args)
4
function step(data){
5
const res = g.next(data)
6
if(!res.done){
7
Promise.resolve(res.value).then(step)
8
}else{
9
resolve(res.value)
10
}
11
}
12
step()
13
})
14
}
Copied!
完整实现
1
const wrap = (genFn) =>{
2
return (...args) => new Promise((resolve, reject) => {
3
const g = genFn(...args)
4
function stepF(nextFn){
5
try{
6
const res = nextFn()
7
} catch (e){
8
return reject(e)
9
}
10
if(res.done){
11
return resolve(res.value)
12
}
13
14
Promise.resolve(res.value).then( v => {
15
stepF( () => g.next(v))
16
}, e => {
17
stepF( () => g.throw(e))
18
})
19
}
20
stepF( () => g.next())
21
})
22
}
Copied!
复制链接