Last active
February 4, 2023 16:58
-
-
Save dmitry-vsl/4dba728f548bdc2352a73564868cef41 to your computer and use it in GitHub Desktop.
Simple suspend implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"type": "module"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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