Created
April 1, 2016 09:59
-
-
Save asvny/3e76f9fb9701f86fc173ee6579e813ea to your computer and use it in GitHub Desktop.
async in js
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
function async(genFunc) { | |
var gen = genFunc(); | |
function step(value) { | |
var next = gen.next(value); | |
var promise = next.value; | |
return promise | |
.then((v) => { | |
if (!next.done) { | |
step(v); | |
} | |
}) | |
.catch((e) => gen.throw(e)); | |
} | |
return step(); | |
} | |
function delay(msg) { | |
return new Promise(resolve=>{ | |
setTimeout(()=>{ | |
resolve(msg) | |
},4000) | |
}) | |
} | |
//Promise | |
function App(){ | |
Promise.resolve(delay('Babel !')).then((name)=>{ | |
console.log(`Hola ${name}`); | |
}) | |
} | |
App(); | |
//Async-await | |
async function App_async(){ | |
let msg = await delay('Babel ! async'); | |
console.log(`Hola ${msg}`); | |
} | |
App_async(); | |
//Generators | |
function* App_gen(){ | |
let msg = yield delay('Babel ! generator'); | |
console.log(`Hola ${msg}`); | |
} | |
async(App_gen); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment