Skip to content

Instantly share code, notes, and snippets.

@zhigang1992
Created September 23, 2016 08:06
Show Gist options
  • Save zhigang1992/53f485bc4b6beeb5a770f1ebbc4c55ce to your computer and use it in GitHub Desktop.
Save zhigang1992/53f485bc4b6beeb5a770f1ebbc4c55ce to your computer and use it in GitHub Desktop.
function fakePromise(time, value) {
return new Promise((resolve) => {
setTimeout(()=>resolve(value), time)
})
}
function* networkRequest() {
const value = yield fakePromise(1000, 123)
return yield fakePromise(1000, value + 123)
}
function await(generator, nextValue) {
const {value, done} = generator.next(nextValue)
if (done) { return value }
if (typeof value.then === 'function') {
return value.then((result) => await(generator, result))
} else {
return value
}
}
const async = networkRequest()
await(async).then(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment