// 生成器函数
function * foo () {
console.log('start')
try {
const res = yield 'foo'
console.log(res)
} catch (e) {
console.log(e)
}
}
const generator = foo()
const result = generator.next()
console.log(result)
generator.throw(new Error('Generator error'))
管理异步流程
递归
function * main () {
const users = yield ajax('/api/users.json')
console.log(users)
const posts = yield ajax('/api/posts.json')
console.log(posts)
}
const g = main()
const result = g.next()
result.value.then(data => {
const result2 = g.next(data)
if (result2.done) return
result2.value.then(data => {
const result3 = g.next(data)
if (result3.done) {
result3.value.then(data => {
const result4 = g.next(data)
})
}
})
})
function * main () {
try {
const users = yield ajax('/api/users.json')
console.log(users)
const posts = yield ajax('/api/posts.json')
console.log(posts)
} catch(e) {
console.log(e)
}
}
const g = main()
function handleResult (result) {
if (result.done) return
result.value.then(data => {
handleResult(g.next(data))
}, error => {
g.throw(error)
})
}
handleResult(g.next())
function co (generator) {
const g = generator()
function handleResult (result) {
if (result.done) return
result.value.then(data => {
handleResult(g.next(data))
}, error => {
g.throw(error)
})
}
handleResult(g.next())
}
co(main)
执行器函数,线上成熟库地址 https://github.com/tj/co
Async/Await语法糖作用一致
网友评论