Skip to content

Instantly share code, notes, and snippets.

@mcsf
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save mcsf/78f970cde9a3f450dd51 to your computer and use it in GitHub Desktop.

Select an option

Save mcsf/78f970cde9a3f450dd51 to your computer and use it in GitHub Desktop.
defer + promises
const log = console.log.bind(console, '--> ');
const warn = console.warn.bind(console, '!!! ');
export default function deferred(fn) {
return new Promise((res, rej) => {
setTimeout(() => {
try {
res(fn());
} catch (e) {
rej(e);
}
}, 0);
});
}
if (require.main === module) {
log(1);
deferred(() => 20).then(x => deferred(() => x * 2)).then(log);
deferred(() => bogus).then(log, warn);
log(3);
}
/**
* Output:
* --> 1
* --> 3
* !!! [ReferenceError: bogus is not defined]
* --> 40
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment