Javascript async functionality - javascript

I have seen a lot of function examples for async javascript containing setTimeout, AJAX calls, etc.
Obviously these all have a certain delay meaning the flow of the script is impacted. But I was wondering, what if I have something like this:
function init() {
this.initSlider();
this.testLog();
}
function initSlider() {
// find multiple items and build up a slider instance
// for each of these elements.
}
function testLog() {
console.log('test);
}
If initSlider possible takes a long time will it simply run my testLog function first?
I am currently a bit unsure about this. I know there might be plenty of examples on the flow of javascript but I can't find ones where a simple function would just take a longer time to run.

It is totally depend on what is there inside initSlider(). Although initslider() is heavy function and do not contain any asynchronus statement
then testLog() will not execute first.
Javascript stores all statements in callstack and they will be executed one after the other.
If there is asynchronus statement then it removes that statement outof the callstack and there is chance of your testLog() to execute.
so for your question my answer will be DEPENDS ON CODE INSIDE initSlider()

Javascript is a technology that runs single threaded. When you use asynchronous methods like AJAX or setTimeout the javascript engine processes those parts one by one (if one is waiting something than switching to another and then back and etc...). You can see the javascript's power on async tasks with Node.js. I guess this blog is very good to understand the Javascript and async methods: click_me!

Related

What makes a JavaScript function asynchronous?

I am aiming to understand what exactly is it about certain JavaScript functions that make them asynchronous. You could have a function like this:
function someRandomFunction () {
for (let i of everything) {
iterator++
something = true
hello = that + whatever
}
}
Nothing about this function is asynchronous. It does a lot of stuff but it does it very quickly.
But then take a Node.js function like this:
fs.readFile('path/to/file', (err, data) => {
// do something
})
This function is declared to be asynchronous. But why is it? What is the reason behind it?
Is it because it takes a certain amount of time for reading a file to complete, therefore it's asynchronous? Why is that asynchronous when looping through some variables and doing some calculations is not asynchronous?
The 'idea' of something being asynchronous means "we've relinquished control to some other operational code, and we have no idea when that other code will allow us to operate again".
So in your bottom sample, you give control over to node's filesystem operations to read a file. We don't know how large that file is, so there is no way to anticipate how much time it will take to complete. So JavaScript allows us to provide a "callback" that get's fired when the async operation is complete. When the callback is executed, control is returned to our code.
The top example is synchronous because your code maintains control over the operation and Javascript executes code synchronously by nature.
A function is either explicitly synchronous or asynchronous; there's no "certain amount of time" that automatically makes it asynchronous.
The important thing to remember with Node is that it's "async I/O", which means nothing is ever async without some input/output to/from the process. You normally see this with file reading/writing, database calls, and anything that requires a network call.
This is a basic but fundamental question. Passing a function to another function doesn't make the code asynchronous automatically. It's all about attemting to work with another piece of code, mostly of unknown origins, probably but not necessarily related with operating system's IO mechanism. In another words you ask something to happen out of the realm of the currently exectuing JS context by handing a task to known or unknown resources which are possibly running on a separate thread.
As i said this can be an IO operation or a database access of which you have no idea on
What code is running
At which thread it is running
How long it will take
Whether it will succeed or not
Behind the curtains these alien codes finally trigger the event queue to invoke the callback function through a driver. In some pure functional languages like Haskell such activities are strictly kept away from the context and must be handled by monadic type functions. In JS this is basically done by asynchronous workflow by callbacks, promises or async-awiat mechanism.
Once you hand out a task to the outer world then there shall be no way for it to interfere with your synchronous code.
In terms of JavaScript, the difference between synchronous and async functions is where and when the code is executed. Synchronous functions are executed immediately one after the other in the current call stack. Async functions are passed off to the event loop, and values returned once the current call stack has completed execution.
Caveat being, nothing in JavaScript is truly asynchronous due to the fact that JS only executes on a single process thread

Are JavaScript List Operations Synchronous?

So I've been doing some research into how JavaScript is actually single threaded even though it appears to be multithreaded (or at least that's how I understand it), and I was wondering if the following function would be guaranteed to complete before some other function is called.
I'm fairly certain that it is, but the call to push() makes me worry that when it is called, some other function may execute first. That being said, I can't think of any sort of long running code that would be ran in push().
// adds a new node to children, after checking if its UID is not in childrenAdded
this.addChild = function(newChild) {
if (!_this._childrenAdded[newChild.uid]) {
_this._childrenAdded[newChild.uid] = true;
_this._children.push(newChild);
}
}
All Array methods, including push, are synchronous. That's pretty much the default for all operations in JS, asynchronous is the exception and documented in every such function.
If a function is asynchronous, it will usually take a callback function as parameter, or return a Promise or something of that kind.
That way you'll always be able to make sure, your code executes after the function has terminated, if that is what you want.
So to answer your question: push is synchronous! :)
Everything in Javascript is synchronous. It might behave and look asynchronous, but that's because everything in javascript is put in an execution stack. Once something is finished, it's popped off the stack.
If you have an event, it's pushed into an event loop. Once everything is popped off the execution stack, it searches the event loop to see if it has anything to run. If it does, then it will run that event. It might look asynchronous, but it's really not.
So, in conclusion. Javascript is synchronous.
The Array push method is synchronous. I highly recommend watching this video on the javascript event loop to understand what goes on behind the scenes.
If you watch it enough times, it should clarify how the "single threaded even though it appears to be multithreaded" part of javascript works. Or maybe it might confuse you more, but hey that's javascript for you!

Waiting in JavaScript beyond wrapping everything in setTimeout

So, I'm creating a bot to play a video game online (completely legally, there's a server for bot competitions, don't worry). The code is in JavaScript, which I'm just picking up now, and I'm having trouble telling the bot to do something, then wait either by time or by condition until doing something else.
So far, I'm simply wrapping everything in gigantic setTimeout commands, but this is extremely inelegant.
There's not too much code that's relevant to post, but essentially I've made up a lot of code that does things like move to a specific location, brake, chase another player, etc. Most work with a recursive setTimeout command - press certain buttons, reset variables, then start the function again if the condition isn't met. If I want to move to a specific location then brake when I finish with that, generally I'd put code likes this:
moveTarget(target);
brake();
[...Execute rest of code...]
However, JavaScript executes both of these commands at the same time, which obviously doesn't work very well. Is there a way to make something more like this (Or the equivalent with a condition instead of a specified time):
moveTarget(target);
wait3Seconds();
brake();
[...Execute rest of code...]
Without needing to do this:
moveTarget(target);
setTimeout(function(){
brake();
[...Execute rest of code...]
},3000);
Given how many of these situations I'll have, my code will end up looking like a gigantic mess of nested setTimeouts, which is not very pretty. Is there a better way? I'm already using JQuery, so I'm perfectly willing to use that if necessary.
A little background...
JavaScript does not handle concurrency in the same way as other programming languages you may be used to. Instead, JavaScript has only the one main thread, and instead has a queue for registering then handling events in order as they occur.
For this reason, it is very important to not do things that would block the thread for long periods of time (like a function such as Thread.sleep() would do). That is why you instead should use setTimeout or setInterval for things like this.
You could always create a custom sleep function to write code in the style you are requesting. This might be something like:
function sleep(millis) {
var startTime = Date.now();
while (Date.now() < startTime + millis) {}
}
But this would be VERY, VERY BAD. This would freeze the page while this sleep function is running.
Back to your problem...
You basically need to refactor your code to be more "eventful". Rather than having large, linear chunks of code within the same block, you should write your JavaScript code to use callbacks and timeouts.
So the last code block you showed is really the paradigm you should be following with JavaScript:
moveTarget(target);
setTimeout(function(){
brake();
[...Execute rest of code...]
},3000);
However, you can certainly clean things up a LOT, if instead of [...Execute rest of code...], you split that apart into other functions and call them from within your setTimeout callback. Of course, keeping your code blocks small and concise is a good rule of thumb in any programming language.
You might also interested in checking out the request animation frame function.
There isn't really a better way to do that. The reason is that any sort of waiting is going to trigger a task that goes into the task queue. Since javascript is single threaded, it has to use these task queues and as a result it will just keep on executing instructions past the setTimeout if instructions are present.
In order to execute code after your delay, it has to be in the timeout callback or it will execute immediately.
You could do this if you created all of your methods in a chain that had a wait command, similar to the jQuery queue system.
$("<div>").queue(function(next){
// do a
a();
next();
}).delay(3*1000).queue(function(next){
// after 3 seconds do b
b();
next();
}).delay(3*1000).queue(function(next){
// after 3 more seconds do c
c();
next();
}).dequeue(); //.dequeue() starts it, only has to be called to make a queue that isn't currently running begin.
so all you would have to do is maintain the same chain and keep adding to it.

Node JS Code Execution

I'm getting slightly annoyed now after reading many different articles on how to write proper code in node js.
I would just like some clarification on whether I'm correct or not with each of these statements:
Code is executed synchronously
A for loop or while loop etc. will be executed asynchronously
By doing the code below isn't proper asynchronous:
L
function doSomething(callback) {
// doing some code
// much much code
callback();
}
The reason that people are saying that this won't work properly is that code is executed asynchronously, so the callback won't be fired off at the end of the code it will all be executed at once.
So for example if you were filling some object by doing some stuff and you wanted to post that full object back through the callback it doesn't work because it will all be executed at the same time.
No, for and while loops are synchronous in Node.js.
Whether your doSomething function example will work or not all depends on whether you're making any calls to asynchronous functions before calling callback(). If you're making asynchronous calls, then you'd need to postpone calling callback() until those asynchronous calls have completed. If you're only making synchronous calls, then you don't need to use a callback and your function can synchronously return the result.
Code in node.js isn't standardly asynchronous. Calls that you place one after another will still be executed one after another. A for or while loop will still block the main code in this way.
However, you can pass around functions which will be executed later, through process.nextTick(callback). This method will add a function to the event queue, which node.js takes care of internally. This will only be executed after any other blocking code has been extecuted. An example:
function doWork(callback) {
//Do some work here, for instance a for loop that might take a while
callback(workReslt);
}
function workDone(workResult) {
//Process the result here
}
function startWork() {
process.nextTick(doWork(workDone));
}
This will execute doWork() when the server passes through the event loop again. This way, the startWork() function will not block the main code.
However, most modules in node.js already implement this. Database and file access is usually non-blocking, it will simply fire a callback when it is done with it's work.
If you really have to perform heavy async calculations (or perhaps some IO that doesn't already have a module for it), you can look into the async module, which has a nice tutorial here: http://justinklemm.com/node-js-async-tutorial/
As for coding conventions, think of it this way. If you know the action is going to take time, you should make it asynchronous (either through the method I mentioned first or the async module). Actions like these are usually related to I/O, which usually also means there is already an asynchronous module for it. However, most cases I have come across up to now, have never required this.
Sources:
http://howtonode.org/understanding-process-next-tick

Is Javascript synchronous(blocking) or Asynchronous(nonblocking) by default

I am trying to grasp on Javascript Asynchronous functions and callbacks.
I got stuck on the concept of callback functions, where I am reading on some places: they are use to have sequential execution of code (mostly in context of jquery e.g animate)and some places specially in the context of Nodejs; they are use to have a parallel execution Asynchronous and avoid blocking of code.
So can some expert in this topic please shed light on this and clear this fuzz in my mind (examples??).
so I could make my mind for the usage of callback function
or that is solely depends on the place of where you are calling/placing a callback function in your code? .
Thanks,
P.S: I am scared that this question would be close as subjective but still I could expect concrete answer for this (perhaps some examples)
Edit: actually this is the example from internet which makes me ambigous:
function do_a(){
// simulate a time consuming function
setTimeout( function(){
console.log( '`do_a`: this takes longer than `do_b`' );
}, 1000 );
}
function do_b(){
console.log( '`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`' );
}
do_a();
do_b();
Result
`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`
`do_a`: this takes longer than `do_b`
when JS is sequential then do_b should always come after do_a according to my understanding.
The core of JavaScript is largely synchronous, in that functions complete their task fully, before completing. Prior to the advent of AJAX, it was really only setTimeout and setInterval that provided asynchronous behavior.
However, it's easy to forget that event handlers are, effectively async code. Attaching a handler does not invoke the handler code and that code isn't executed until some unknowable time in the future.
Then came AJAX, with its calls to the server. These calls could be configured to be synchronous, but developers generally preferred async calls and used callback methods to implement them.
Then, we saw the proliferation of JS libraries and toolkits. These strove to homogenize different browsers' implementations of things and built on the callback approach to async code. You also started to see a lot more synchronous callbacks for things like array iteration or CSS query result handling.
Now, we are seeing Deferreds and Promises in the mix. These are objects that represent the value of a long running operation and provide an API for handling that value when it arrives.
NodeJS leans towards an async approach to many things; that much is true. However this is more a design decision on their part, rather than any inherent async nature of JS.
Javascript is always a synchronous(blocking) single thread language but we can make Javascript act Asynchronous through programming.
Synchronous code:
console.log('a');
console.log('b');
Asynchronous code:
console.log('a');
setTimeout(function() {
console.log('b');
}, 1000);
setTimeout(function() {
console.log('c');
}, 1000);
setTimeout(function() {
console.log('d');
}, 1000);
console.log('e');
This outputs: a e b c d
In node long running processes use process.nextTick() to queue up the functions/callbacks. This is usually done in the API of node and unless your programming(outside the api) with something that is blocking or code that is long running then it doesn't really effect you much. The link below should explain it better then I can.
howtonode process.nextTick()
jQuery AJAX also takes callbacks and such as it its coded not to wait for server responses before moving on to the next block of code. It just rememebers the function to run when the server responds. This is based on XMLHTTPRequest object that the browsers expose. The XHR object will remember the function to call back when the response returns.
setTimeout(fn, 0) of javascript will run a function once the call stack is empty (next available free tick) which can be used to create async like features.setTimeout(fn, 0) question on stackoverflow
To summerise the async abilities of javascript is as much to do with the environments they are programmed in as javascript itself. You do not gain any magic by just using lots of function calls and callbacks unless your using some API/script.
Jquery Deferred Object Is another good link for async capabilities of jQuery. Googling might find you information on how jQuery Deferred works also for more insight.
In JavaScript the term "asynchronous" typically refers to code that gets executed when the call stack is empty and the engine picks a job from one of its job queues for execution.
Once code is being executed, it represents a synchronous sequence of execution, which continues until the call stack is empty again. This sequence of execution will not be interrupted by events in order to execute some other JavaScript code (when we discard Web Workers). In other words, a single JavaScript environment has no preemptive concurrency.
While synchronous execution is ongoing, events might be registered as jobs in some job queues, but the engine will not process those before first properly execution what is on the call stack. Only when the call stack is empty will the engine take notice of the job queues, pick one according to priority, and execute it (and that is called asynchronous).
Callbacks
Callbacks can be synchronous or asynchronous -- this really depends on how they are called.
For instance, here the callback is executed synchronously:
new Promise(function (resolve) { /* .... */ });
And here the callback is executed asynchronously:
setTimeout(function () { /* ... */ });
It really depends on the function that takes the callback as argument; how it deals with eventually calling that callback.
Ways to get code to execute asynchronously
The core ECMAScript language does not offer a lot of ways to do this. The well-known ones are offered via other APIs, such as the Web API, which are not part of the core language (setTimeout, setInterval, requestAnimationFrame, fetch, queueMicrotask, addEventListener, ...).
Core ECMAScript offers Promise.prototype.then and (depending on that) await. The callback passed to then is guaranteed to execute asynchronously. await will ensure that the next statements in the same function will be executed asynchronously: await makes the current function return, and this function's execution context will be restored and resumed by a job.
It also offers listening to when the garbage collector is about to garbage collect an object, with FinalizationRegistry.
Web Workers
Web Workers will execute in a separate execution environment, with their own call stack. Here preemptive concurrency is possible. When the term asynchronous is used in the JavaScript world, it typically does not refer to this kind of parallelism, although the communication with a Web Worker happens via asynchronous callback functions.
Javascript by default is "synchronous", it's the web APIs that handle "asynchronous" behaviour.
As for the setTimeout example,
console.log(...), in the global scope works straight away, while those inside functions wrapped inside setTimeout, wait inside the callback queue only to be pushed back on the call stack once ready. Thus they take time. Also, the time specified is not exact but the minimum time after which that piece of code can run anytime.
Thanks !

Categories

Resources