Naveen Reddy
I ❤️ building useful stuff!! Passionate about coding and design.
Concurrency vs Parallelism
Terminology
So what happens if we block JavaScript??
There are few things that will block javascript
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
}, 3000);
}
Event Loop in JavaScript
Callbacks
Callback Hell ??
Promises
Ok, Let's talk about Promises
Pros
But we are still doing callbacks inside .then(callbackFn)
Can we do better ??
What we want??
let promise = fetch('/url');
//Somehow we don't need to do a .then() and get the result
console.log(promise.result)
But JavaScript is single threaded, we can't block.
function * genFunc(){
let result = fetch('/url');
// pause the execution
yield result;
// resume the execution
return result;
}
It is basically a thin layer of abstraction of Promises and Generators
async function getUsers(){
// Magic code
let result = await fecth('/url');
return result;
}
By Naveen Reddy