Skip to content

Instantly share code, notes, and snippets.

@dmitry-vsl
Last active February 4, 2023 16:58
Show Gist options
  • Save dmitry-vsl/4dba728f548bdc2352a73564868cef41 to your computer and use it in GitHub Desktop.
Save dmitry-vsl/4dba728f548bdc2352a73564868cef41 to your computer and use it in GitHub Desktop.
Simple suspend implementation
{"type": "module"}
function suspend(gen) {
function next(result){
if(result.done){
return result.value
} else {
if(result.value instanceof Promise) {
return result.value.then(
value => next(gen.next(value)),
error => next(gen.throw(error)),
)
} else {
return next(gen.next(result.value))
}
}
}
return next(gen.next())
}
const x = await suspend(function*() {
const x = yield Promise.resolve(1)
console.log('x', x)
try {
yield Promise.reject('error!')
} catch(e) {
console.log('error caugh', e)
}
const timeout = yield new Promise(res => setTimeout(() => res('timeout!'), 1000))
console.log(timeout)
return x
}())
console.log('finally x is', x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment