Skip to content

Instantly share code, notes, and snippets.

@lqt0223
Created November 18, 2023 09:36
Show Gist options
  • Save lqt0223/de0201ec6726b5f7348ee66dabe57d1d to your computer and use it in GitHub Desktop.
Save lqt0223/de0201ec6726b5f7348ee66dabe57d1d to your computer and use it in GitHub Desktop.
41 async-await style in generator
function apiReq(result, delay) {
return new Promise(resolve => {
setTimeout(() => {
resolve(result)
}, delay*1000)
})
}
// the generator function version of async-await programming scheme
// function* -> async
// yield -> await
function* routine() {
console.log('a')
const a = yield apiReq(5, 1)
console.log('b')
const b = yield apiReq(4 + a, 2)
console.log('c')
const c = yield apiReq(3 + b, 1)
console.log('result')
return c
}
// co - the function runner that can follow the promise chain yielded, and execute async procedures in sequence
function co(generator) {
// run once
function tick(curValue) {
const res = generator.next(curValue) // the parameter will become result of a yield expression
let { value, done } = res
if (!(value instanceof Promise)) {
value = Promise.resolve(value)
}
return value.then((resolvedValue) => {
if (!done) {
return tick(resolvedValue)
} else {
return resolvedValue
}
})
}
return tick(undefined)
}
const result = co(routine())
result.then(res => {
console.log(res)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment