Skip to content

Instantly share code, notes, and snippets.

@InfiniteXyy
Created October 9, 2020 09:57
Show Gist options
  • Save InfiniteXyy/dae0653c0a517fab8d442a263a17f544 to your computer and use it in GitHub Desktop.
Save InfiniteXyy/dae0653c0a517fab8d442a263a17f544 to your computer and use it in GitHub Desktop.
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