Created
October 9, 2020 09:57
-
-
Save InfiniteXyy/dae0653c0a517fab8d442a263a17f544 to your computer and use it in GitHub Desktop.
This file contains 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 myAsync(generatorFactory) { | |
return (...args) => { | |
const generator = generatorFactory(...args); | |
const resolve = (result) => { | |
if (result.done) { | |
return Promise.resolve(result.value); | |
} | |
return Promise.resolve(result.value) | |
.then((resolvedValue) => resolve(generator.next(resolvedValue))) | |
.catch((error) => generator.throw(error)); | |
}; | |
return resolve(generator.next()); | |
}; | |
} | |
// example | |
const fetchResult = myAsync(function* (param) { | |
yield new Promise((resolve) => setTimeout(resolve, 1000)); | |
return `{ data: ${param} }`; | |
}); | |
const main = myAsync(function* () { | |
const result = yield fetchResult("123"); | |
console.log("result is: " + result); | |
}); | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment