Last active
December 7, 2015 09:00
-
-
Save nulltask/beff73004cd21cd93f4c to your computer and use it in GitHub Desktop.
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
| // returns promise. | |
| function foo() { | |
| return new Promise(function(resolve, reject) { | |
| setTimeout(function() { | |
| if (Math.random() < .5) { | |
| resolve(Math.random()); | |
| } else { | |
| reject(new Error(Math.random())); | |
| } | |
| }, 1000); | |
| }); | |
| } | |
| // async function. | |
| async function bar() { | |
| console.log('this is bar.'); | |
| while (true) { | |
| try { | |
| var ret = await foo(); | |
| console.log(ret); | |
| } catch (e) { | |
| console.log(e); | |
| } | |
| } | |
| } | |
| // async function. (inline promise) | |
| async function baz() { | |
| console.log('this is baz.'); | |
| while (true) { | |
| try { | |
| var ret = await new Promise(function(resolve, reject) { | |
| setTimeout(function() { | |
| if (Math.random() > 0.5) { | |
| resolve('resolve'); | |
| } else { | |
| reject(new Error('Error')); | |
| } | |
| }, Math.random() * 1000); | |
| }); | |
| console.log(ret); | |
| } catch (e) { | |
| console.log(e); | |
| } | |
| } | |
| } | |
| // call async functions. | |
| console.log('async function bar() calling...'); | |
| console.log('bar', bar()); | |
| console.log('async function baz() calling...'); | |
| console.log('baz', baz()); |
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
| $ babel-node test.js | |
| async function bar() calling... | |
| this is bar. | |
| bar Promise { | |
| _d: | |
| { p: [Circular], | |
| c: [], | |
| a: undefined, | |
| s: 0, | |
| d: false, | |
| v: undefined, | |
| h: false, | |
| n: false } } | |
| async function baz() calling... | |
| this is baz. | |
| baz Promise { | |
| _d: | |
| { p: [Circular], | |
| c: [], | |
| a: undefined, | |
| s: 0, | |
| d: false, | |
| v: undefined, | |
| h: false, | |
| n: false } } | |
| [Error: Error] | |
| resolve | |
| 0.7497521410696208 | |
| resolve | |
| [Error: Error] | |
| resolve | |
| 0.1544457538984716 | |
| [Error: Error] | |
| [Error: 0.8831553251948208] | |
| [Error: Error] | |
| 0.07748340792022645 | |
| resolve | |
| resolve | |
| 0.4588852066081017 | |
| resolve | |
| [Error: Error] | |
| [Error: 0.8220234394539148] | |
| [Error: Error] | |
| [Error: 0.5263843222055584] | |
| resolve | |
| [Error: Error] | |
| [Error: Error] | |
| 0.5478959816973656 | |
| ^C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment