Skip to content

Instantly share code, notes, and snippets.

@winsonwq
Created January 3, 2012 08:24
Show Gist options
  • Select an option

  • Save winsonwq/1554065 to your computer and use it in GitHub Desktop.

Select an option

Save winsonwq/1554065 to your computer and use it in GitHub Desktop.
How to use $await in Mr.Async
// 一个实现了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