Skip to content

Instantly share code, notes, and snippets.

@nexpr
Last active February 23, 2016 14:09
Show Gist options
  • Select an option

  • Save nexpr/49e491549c7f16705a2f to your computer and use it in GitHub Desktop.

Select an option

Save nexpr/49e491549c7f16705a2f to your computer and use it in GitHub Desktop.
use generator like async/await
/* library function */
function async(args, gen){
return new Promise((resolve, reject) => {
var ite = gen(...args)
!function recur(pre_value){
var ret = ite.next(pre_value)
ret.done ? resolve(ret.value) : ret.value.then(recur)
}()
})
}
/* sample 1 */
function wait(msec){
return new Promise((resolve, reject) => {
setTimeout(resolve, msec)
})
}
function async_test(){
return async(arguments, function*(a,b){
console.log("wait", Date.now())
yield wait(1000)
console.log("waitend", Date.now())
console.log(a, b)
})
}
async_test(1, 2)
// wait 1455961206662
// waitend 1455961207666
// 1 2
/* sample 2 */
function test(){return async(arguments, function*(){
var f1 = fetch("/").then(e => e.text())
var f2 = fetch("/test.jpg").then(e => e.blob())
var text = yield f1
console.log(text.substr(0,14))
var blob = yield f2
console.log(blob)
})}
test()
// <!doctype html
// Blob {}
function acall(gen, ...args){
var ite = gen(...args)
!function recur(pre_value){
var ret = ite.next(pre_value)
ret.done || ret.value(recur)
}()
}
function afunc(fn, ...args){
return cb => fn(...args, cb)
}
function httpGet(url, cb){
fetch(url).then(e => e.text()).then(e => cb(e))
}
function wait(msec, cb){
setTimeout(cb, msec)
}
function* sample_gen(message){
console.log("wait", Date.now())
yield afunc(wait, 1000)
console.log("waitend", Date.now())
var text = yield afunc(httpGet, "/")
console.log(message)
console.log(text)
}
acall(sample_gen, "この後にURLのデータ:")
wait 1455345512307
waitend 1455345513308
この後にURLのデータ:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTM...............
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment