Last active
June 17, 2018 13:32
-
-
Save Yengas/6b2d88fe96507cc9041118bb603fe483 to your computer and use it in GitHub Desktop.
Simple implementation of async/await workflow with generators and yield.
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 doSomething(){ | |
return Promise.resolve(73); | |
} | |
function timeout(ms){ | |
return new Promise((resolve) => setTimeout(resolve, ms, ms)); | |
} | |
function asyncFlow(generatorFunc){ | |
const generator = generatorFunc(); | |
function callGeneratorSafeWithParam(param = undefined, throws = false){ | |
try{ | |
const { value, done } = throws ? generator.throw(param) : generator.next(param); | |
const promise = value instanceof Promise ? value : Promise.resolve(value); | |
if(done) | |
return promise; | |
else | |
return promise.then(resultCallback, errCallback); | |
}catch(err){ | |
return Promise.reject(err); | |
} | |
} | |
function errCallback(err){ | |
return callGeneratorSafeWithParam(err, true); | |
} | |
function resultCallback(res){ | |
return callGeneratorSafeWithParam(res); | |
} | |
return callGeneratorSafeWithParam(undefined); | |
} | |
asyncFlow(function* test(){ | |
const value = yield doSomething(); | |
console.log('Got result of the promise:', value); | |
console.log('Waiting 3 seconds before finishing.'); | |
const time = yield timeout(3000); | |
console.log('Waiting time in ms:', time); | |
// extra wait just for fun | |
yield timeout(1000); | |
return value; | |
}).then((res) => console.log('Should print the value from doSomething(73):', res)); | |
asyncFlow(function* test2(){ | |
throw new Error('wtf'); | |
}).catch((err) => console.log('Should end with wtf error:', err)); | |
asyncFlow(function* test3(){ | |
// should drop in to global unhandled promise rejection | |
Promise.reject('first'); | |
console.log('--- Should see this.'); | |
// should be returned as a result of this function(promise rejection) | |
yield Promise.reject('second'); | |
console.log('--- Should not see this.'); | |
}).catch((err) => console.log('Should fail on the second error:', err)); | |
asyncFlow(function* test4(){ | |
try{ | |
yield Promise.reject('wut'); | |
console.log('---- Should not see this.'); | |
}catch(err){ | |
console.log('---- Should see this.'); | |
} | |
console.log('---- Should see this aswell.'); | |
return 73; | |
}).then((res) => console.log('Response of test4:', res), (err) => console.log('Error on test4:', err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment