Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveennagan/4099b3f944aee88c0d497cef2a83fe5b to your computer and use it in GitHub Desktop.
Save naveennagan/4099b3f944aee88c0d497cef2a83fe5b to your computer and use it in GitHub Desktop.
Async Await using Promises and Generators.
var asyncTask1=()=>{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve({message:"Done the AsyncTask 1 "});
},100);
})
}
var asyncTask2=()=>{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve({message:"Done the AsyncTask 2 "});
},100);
})
}
var asyncAwait=function* (){
var result1=yield asyncTask1();
console.log(result1);
var result2=yield asyncTask2();
console.log(result2);
}
var asyncRunner = (genFunction)=>{
var genFunctionGenerator = genFunction();
runGenerator();
function runGenerator(val){
var promiseResult= genFunctionGenerator.next(val);
//Now keep on checking whether this is resolve are not.
if(promiseResult.done){
return promiseResult.value;
}
else{
// wait for sometime to check whether promise was resolved
Promise.all([promiseResult.value]).then((results)=>{
runGenerator(results[0]);
})
}
}
}
var asyncAwaitGenerator = asyncRunner(asyncAwait);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment