Skip to content

Instantly share code, notes, and snippets.

@rBurgett
Last active December 26, 2016 19:23
Show Gist options
  • Save rBurgett/670dba198200c4d86d7073d509a40ebc to your computer and use it in GitHub Desktop.
Save rBurgett/670dba198200c4d86d7073d509a40ebc to your computer and use it in GitHub Desktop.
Promises and generators examples for Jeff
const co = require('co');
// Asynchronous examples
// Callback function
setTimeout(() => {
console.log('This is a callback function!');
}, 100);
// Promise-returning function example
const promiseReturningFunc = name => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(name);
}, 100);
});
};
{
// const name = promiseReturningFunc('Ryan');
// This won't work, because name will be a Promise, not a value
console.log(name);
// This will work
promiseReturningFunc('Ryan')
.then(name => {
console.log(name);
})
.catch(err => {
console.error(err);
});
}
co(function*() {
try {
const names = ['Ryan', 'Hannah Joy', 'Rand'];
// const name = yield promiseReturningFunc('Ryan');
// console.log(name);
for (const n of names) {
const name = yield promiseReturningFunc(n);
console.log(name);
}
} catch (err) {
console.error(err);
}
});
//example of promise-returning function with generator internally
const convert = () => {
return new Promise((resolve, reject) => {
co(function*() {
try {
const name = yield promiseReturningFunc('Ryan');
resolve();
} catch (err) {
reject(err);
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment