Skip to content

Commit 2d1ff9f

Browse files
committed
async mechanism
1 parent 548d6ce commit 2d1ff9f

File tree

5 files changed

+75
-14
lines changed

5 files changed

+75
-14
lines changed

Javascript/setTimeout-Absolute-Basics.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ Again - From MDN setTimeout(): - "Code executed by setTimeout() is run in a sepa
8686

8787
#### But does this mean it executes in parallel to any other code that is currently in process?
8888

89-
No, it doesn't. "Execution context" doesn't mean "thread". setTimeout code has absolutely no parallelism going on
89+
No, it doesn't. "Execution context" doesn't mean "thread". setTimeout code has absolutely no parallelism going on inside it. The "separate execution context" mentioned in the documentation just means that the this reference will be different than in the function where setTimeout() is called.
90+
A Javascript engine simply processes a queue of events sequentially on a single thread. When the event queue is empty, that thread idles. In a browser, events are added to the queue by user input, page loading, etc. In node.js events can also be HTTP requests or hardware events. And setTimeout() simply adds another kind of event with the additional condition that it should only be added to the queue after a certain time has passed.
9091

9192
[https://johnresig.com/blog/how-javascript-timers-work/](https://johnresig.com/blog/how-javascript-timers-work/)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
One of Javascript’s strength is the way it handles asynchronous (async) code. Instead of getting blocked, the thread is pushed in an event queue which gets fired after the execution of all the other codes. This means that you can let your code do several things at the same time without stopping or locking your main thread.
2+
3+
```js
4+
Console.log( “a” );
5+
setTimeout(function () {
6+
Console.log( “c”)
7+
}, 500 );
8+
setTimeout(function () {
9+
Console.log( “d” )
10+
}, 500);
11+
setTimeout(function () {
12+
Console.log( “e” )
13+
}, 500);
14+
Console.log( “b” );
15+
```
16+
17+
The code above will result with the console displaying “a” and “b” first, then after 500 milliseconds, “c”, “d” and “e” will be displayed.
18+
19+
Note that a timeout will only be executed after all the code in a block has finished executing. If a long-running function is set before the timeout then the function will have to finish executing first before the setTimeout function gets executed.
20+
21+
#### Basically, async functions like setTimeout and setInterval are pushed into a special queue known as the “event loop”.
22+
23+
## The Event Loop - Its a first-in-first-out task queue, or FIFO Queue.
24+
25+
The event loop is a special queue for callback functions. When an async code is executed, a callback is then pushed into the queue. The Javascript engine will only execute the event loop if the code after the async function has finished executing. This is because, Javascript is single threaded.
26+
27+
**The event loop is a first-in-first-out type of queue – callbacks are processed in order they were added to the queue.**
28+
29+
## The Call Stack - Its a LIFO queue .
30+
31+
The event loop (Which on the other hand is FIFO) continuously checks the call stack to see if there’s any function that needs to run.
32+
33+
While doing so, it adds any function call it finds to the call stack and executes each one in order.
34+
35+
JavaScript has a single call stack in which it keeps track of what function we’re currently executing and what function is to be executed after that. But first — what’s a stack? A stack is an array-like data structure but with some limitations — you can only add items to the back and only remove the last item. Another example is a pile of plates — you put them on top of each other and at any time you can only remove the top one.
36+
37+
When you’re about to execute a function it is added on the call stack. Then if that function calls another function — the other function will be on top of the first one in the call stack. When you get an error in the console you get a long message that shows you the path of execution — this is what the stack looked in that exact moment. But what if we make a request or put a timeout on something? In theory that should freeze the entire browser until it is executed so the call stack can continue? In practice however, you know that this doesn’t happen — because of the Event Table and Event Queue.
38+
39+
#### Further Reading
40+
41+
[https://www.hiddenwebgenius.com/guides/understanding-javascripts-asynchronous-code/](https://www.hiddenwebgenius.com/guides/understanding-javascripts-asynchronous-code/)
42+
43+
[https://hackernoon.com/understanding-js-the-event-loop-959beae3ac40](https://hackernoon.com/understanding-js-the-event-loop-959beae3ac40)

Promise-Async-Await-Sequential-Execution/async-await-master-notes/async-await-1.js

+13-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
require("es6-promise").polyfill();
2-
require("isomorphic-fetch");
1+
require("es6-promise").polyfill()
2+
require("isomorphic-fetch")
33

44
/* I had to use the above packages as without it the simple fetch.('url') wont work
55
https://stackoverflow.com/questions/36484156/es6-fetch-is-undefined
@@ -13,15 +13,15 @@ getJSON = () => {
1313
// The data from the request is available in a .then block
1414
// We return the result using resolve.
1515
.then(json => {
16-
resolve(json);
17-
console.log("Successively fetched");
18-
});
19-
});
20-
};
16+
resolve(json)
17+
console.log("Successively fetched")
18+
})
19+
})
20+
}
2121

22-
getJSON(); // Will fetch and then print "Successively fetched"
22+
getJSON() // Will fetch and then print "Successively fetched"
2323

24-
/* EXPLANATION OF THE ABOVE - The Fetch API provides an interface for making network requests, returning Promises for us to resolve. To use it to get the data, I chain together a single .then callback. The callback receives the Response object and return back its JSON data. And then console.logs it.
24+
/* EXPLANATION OF THE ABOVE - The Fetch API provides an interface for making network requests, returning Promises for us to resolve. To use it to get the data, I chain together a single .then() callback. The callback receives the Response object and return back its JSON data. And then console.logs it.
2525
*/
2626

2727
/* REMEMBER THE FETCH SYNTAX
@@ -42,12 +42,12 @@ fetch(url) // Call the fetch function passing the url of the API as a parameter
4242

4343
const getJSONAsync = async () => {
4444
// The await keyword saves us from having to write a .then() block.
45-
let json = await fetch("https://tutorialzine.com/misc/files/example.json");
45+
let json = await fetch("https://tutorialzine.com/misc/files/example.json")
4646

47-
return json && console.log("Fetched with async");
48-
};
47+
return json && console.log("Fetched with async")
48+
}
4949

50-
getJSONAsync(); // Will fetch and then print "Fetched with async"
50+
getJSONAsync() // Will fetch and then print "Fetched with async"
5151

5252
/* The await expression causes async function execution to pause until a Promise is resolved, that is fulfilled or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.
5353
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/* Making setTimeout an async/await function. On more than one occasion I’ve wanted to wait a number of seconds in JavaScript. Normally,setTimeout() is fine for this, but what about the case when you are using async/await syntax?
2+
3+
And an simple example of its use, perhaps looping over some API calls but delaying a second between each (rate limiting) - So your api calls dont get blocked for hitting the API
4+
*/
5+
const wait = async ms => {
6+
return new Promise(resolve => {
7+
setTimeout(resolve, ms)
8+
})
9+
}
10+
11+
// Now make the api call from an array of Uris given as arguments to the functions, after waiting 1000 ms between each
12+
const doRequest = async uris => {
13+
for (let uri of uris) {
14+
await fetch(uri)
15+
await wait(1000)
16+
}
17+
}

0 commit comments

Comments
 (0)