Created
May 29, 2021 14:20
-
-
Save justinline/392312f46a6c960bb43387eb84bc2065 to your computer and use it in GitHub Desktop.
async/await with generators
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
// Recursively evaluates generator values | |
function customAsync(generatorFn) { | |
const generator = generatorFn(); | |
const resolve = (generatorResult) => { | |
const noMoreIterations = generatorResult.done; | |
if (noMoreIterations) { | |
return Promise.resolve(generatorResult.value); | |
} | |
return Promise.resolve(generatorResult.value) | |
.then((newValue) => resolve(generator.next(newValue))) | |
.catch((error) => resolve(generator.throw(error))); | |
}; | |
return resolve(generator.next()); | |
} | |
describe('customAsync', () => { | |
it('should await the values of the function', () => | |
customAsync(function* () { | |
const result = yield Promise.resolve('My API value'); | |
expect(result).toBe('My API value'); | |
})); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment