Created
July 30, 2018 12:43
-
-
Save naveennagan/4099b3f944aee88c0d497cef2a83fe5b to your computer and use it in GitHub Desktop.
Async Await using Promises and Generators.
This file contains 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
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