Skip to content

Instantly share code, notes, and snippets.

@edward-hsu-1994
Last active August 29, 2015 14:16
Show Gist options
  • Save edward-hsu-1994/1492e2fb2017c651ebe5 to your computer and use it in GitHub Desktop.
Save edward-hsu-1994/1492e2fb2017c651ebe5 to your computer and use it in GitHub Desktop.
javascript使用yield模擬await功能
function requestAsync(path,thread){
var q = new XMLHttpRequest();
q.open('get','test.json');
q.onload = function(){
requestAsync['result'] = JSON.parse(q.response);
thread.next();//回呼
}
q.send();
}
function async(func,args){
var result = func.apply(func,args);
func["thread"] = result;//thread
result.next();
}
async(function*(){
yield requestAsync('test.json',this.thread);
var temp = requestAsync.result;//取得結果後執行
console.log(temp.message1 + " " + temp.message2);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment