Last active
August 29, 2015 14:22
-
-
Save mcsf/78f970cde9a3f450dd51 to your computer and use it in GitHub Desktop.
defer + promises
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
| 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