Created
January 3, 2012 08:24
-
-
Save winsonwq/1554065 to your computer and use it in GitHub Desktop.
How to use $await in Mr.Async
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
| // 一个实现了Mr.Deferred的通用异步方法 | |
| // 等待一秒钟,计算一个0到1的随机数 | |
| function asyncRandom(callback){ | |
| var de = Mr.Deferred(); | |
| setTimeout(function(){ | |
| var random = Math.random(); | |
| if(typeof callback == 'function') | |
| callback(random); | |
| de.resolve(random); | |
| }, 1000); | |
| return de; | |
| } | |
| // 接受单个值 | |
| eval(Mr.Async.recode(function(){ | |
| var random = $await(asyncRandom()); | |
| console.log(random); | |
| })); | |
| // 多个值 | |
| eval(Mr.Async.recode(function(){ | |
| var randoms = $await(asyncRandom(), asyncRandom()); | |
| // 返回值为数组 | |
| console.log(randoms[0]); | |
| console.log(randoms[1]); | |
| })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment