I am quiet new to javascript, can not understand that why all javascript calls are asynchronous,
for example, we have calling with order like
call_function1;
call_function2:
if function2 is depend on the results of function1, that can not be ensured, because the execution is asynchronous. Is that true ? And why ?
If true, how to ensure they are synchronous.
If this is duplicated question, I am sorry, because it is quiet new for me.
Thanks fo your answer first.
JavaScript calls are synchonous. If second function depends on results of first function, you might use callbacks model.
function foo(callback) {
var results = // get some results;
callback(results);
}
function boo(results) {
// do something with results here..
}
foo(boo);
No Javascript has functions that guarantee order and behave much like other languages. For example:
function f1() {
alert(1);
}
function f2() {
alert(2);
}
f1();
f2();
You will always get 1 and then 2. What's more is AFAIK javascript runs on one thread so you don't have to worry about race conditions either.
The asynchronous part of javascript comes from waiting on events. For example if you make 2 ajax requests (the a in ajax standing for asynchronous is a hint), you cannot guarantee which will come back first and thus if you have different callbacks for the two requests, you can't guarantee which will be called first.
Calling two functions in a row is definitely not asynchronous.
In fact.. javascript is 100% synchronous. Unless you use 'web workers' all javascript will always run in a single thread, in a single process. There is never, ever a situation where 2 scripts are running at the same time.
Even if you handle an event, coming from an XMLHTTPRequest for instance, the event will only be triggered after all other javascript code has stopped executing.
As mentioned in the comments to your question, JavaScript function calls are usually not asynchronous. The following will be executed in order:
function sayHello() {
console.log("Hi");
}
function sayBye() {
console.log("Bye");
}
sayHello();
sayBye();
The above code will first print "Hi", then "Bye", as the calls to sayHello and sayBye are in that order.
However, if a function does perform some action asynchronously, and you have another function that relies on the result of that, you can supply the second function as a callback to the asynchronous request. For example:
xmlHttpRequestObj.onreadystatechange = function() {
if(xmlHttpRequestObj.readyState == 4 && xmlHttpRequestObj.status == 200) {
//Asynchronous call returned successfully. Do something that relies on that here.
}
}
I don't know how you say that "Javascript is generally said to be asynchronous". It is generally the opposite: Javascript is almost always not asynchronous.
So generally (no ajax, no callback, no event handling), the following functions calls will execute sequentially.
function1();
function2();
If you are assigning both these functions to a single event, both will be called concurrently, but will not be executed in parallel. Same if both are called at the same time (using setTimeout), or as an Ajax callback. See Is JavaScript guaranteed to be single-threaded? for a very good explanation.
You could have heard that Ajax is asynchronous. That is true when you consider the request to servers without interfering with the user, "in the background". But this does not mean that Javascript is asynch. In fact even with Ajax calls, the javascript part is single threaded.
Related
i have a little problem in understand of callbacks. I have read a lot in the last 2 days and what i have understand is the following (correct me, if i'm wrong):
JavaScript is a single thread language and you can program synchronous and asynchronous.
Synchronous means, each statement waits for the previous statement to finish before executing. That can lead into trouble, because if for instance a connection to a database needs a lot of time, the statements after the previous has to wait.
Finally that's very bad and that's why it's better to program asynchronous in Javascript, because Asynchronous code doesn't have to wait, the code can continue to run and the user don't have to wait.
To program asynchronous the Callbacks (functions of higher order) are needed.
Now i have try to program a little example by a lot of tutorials, etc.
function testCallback(a,callback){
console.log('1.function and given parameter: '+a);
callback(10);
}
testCallback(5 , function(x){
console.log("2.function and given parameter of 1. function: "+x);
});
Is that right? the output is:
1.function and given parameter: 5
2.function and given parameter of 1. function: 10
I do not understand, what the advantage is of this code, because i think that can still lead into trouble? If "console.log('1.function and....') has problems, the callback(10) function would even stop or not?
Thanks for any help!
JavaScript is a single thread language...
No, it isn't. The language says nothing about threading. Most environments give you a single thread per global environment, though (and on browsers you can create more, which interoperate through messaging). NodeJS provides just the one thread. Some environments (such as Rhino or Nashorn on the JDK) provide true multi-threading (and all the advantages and hassles that can involve).
Using a callback doesn't make code asynchronous. Your example, for instance, is not asynchronous. Consider:
function testCallback(a,callback){
console.log('1.function and given parameter: '+a);
callback(10);
}
console.log("Before the call");
testCallback(5 , function(x){
console.log("2.function and given parameter of 1. function: "+x);
});
console.log("After the call");
Note how we don't see After the call until after 2.function and given parameter of 1. function: 10. If the callback were asynchronous, we'd see it before:
function testCallback(a,callback){
console.log('1.function and given parameter: '+a);
setTimeout(function() { // Using setTimeout
callback(10); // to make this call
}, 0); // asynchronous
}
console.log("Before the call");
testCallback(5 , function(x){
console.log("2.function and given parameter of 1. function: "+x);
});
console.log("After the call");
Whether a callback is called synchronously or asynchronously depends entirely on what the function you're passing it to does. For instance, the callback used by Array#sort is called synchronously, but the callback used by setTimeout is called asynchronously.
For code to be asynchronous, it has to start an operation and then have that operation complete later, triggering a callback. setTimeout does that, as does ajax when used correctly, as do a wide range of other things.
Note that callbacks are currently how you handle asynchronous behavior (simple callbacks like the above, or promise callbacks), but the next specification (ES2017) will define built-in language semantics for dealing with asynchronousity without callbacks in the form of async and await. You can use that syntax today if you transpile with a tool like Babel.
In javascript callbacks can be synchronous or asynchronous. Synchronous callbacks can have a lot of benefits, but they don't do anything to stop your code blocking.
I think the best way to understand what asynchronous code is, and why it's beneficial, is to learn how Javascript actually evaluates your code. I recommend this video, which explains the process very clearly https://www.youtube.com/watch?v=8aGhZQkoFbQ
A JavaScript Callback Function is a function that is passed as a parameter to another JavaScript function. Callbacks can be synchronous or asynchronous. Simply passing a function as parameter will not change its current behavior.
It's behavior can be changed by the method which will execute it by calling it inside an event listener or setTimeout function etc. Basically event listener or setTimeout etc are handled by webapi in async fashion. If callback functions are inside these functions then these are moved to a queue by webapi when they are activated like button click(event listener) or time declared in setTimeout passed. They will move from queue to stack(if stack is empty) and run on stack finally.
The main advantage of using callback function can be seen from below code :-
var add = function(x,y) {
return x+y;
}
var multiply = function(x,y){
return x*y;
}
var calculate = function(x,y,callback){
return callback(x,y);
}
console.log(calculate(4,9,add));
I know JavaScript is synchronous by nature. So that when I call a function with web API It performs synchronously:
setTimeout(function(){
console.log('1');
}, 2000);
console.log('2');
it will print '2' then '1'.
But when I run a loop like for loop and increase the iteration it executes synchronously:
var first = function(){
for(var i=0;i<=100000000;i++){
if(i==100000000){
console.log('first')
};
};
};
var second = function() {
console.log('second')
};
var a = function() {
first();
second();
}
a();
It will print the first second respectively.
So, is JavaScript performing synchronously with native code?
The first example is asynchronous because you've explicitly asked it to be asynchronous by using setTimeout. setTimeout (and its relation setInterval) explicitly set up an asynchronous timed callback to the function you pass them.
The remaining examples don't use anything that creates asynchronousness like setTimeout (and ajax and such) do, so naturally it's synchronous.
I know javaScript is asynchronous by nature
No, JavaScript (the language) is synchronous by nature. Literally the only asynchronous aspect of JavaScript was added in ES2015 and relates to when the callback passed into a promise's then or catch is called. That's it. setTimeout, for instance, is not part of JavaScript; it's part of the host environment where JavaScript is largely used (browsers). (It's also part of a couple of non-browser host environments, like NodeJS.)
JavaScript is primarily used in an environment that encourages asynchronous operations (browsers) where it's used to respond to user events (asynchronous), ajax completions (asynchronous), and timer callbacks (asynchronous), but the language is almost entirely synchronous.
JS is event-driven, this is why you think its async.. But it only has async features..
for loop does not have any event-callbacks, so its just sync
I got to know that
JavaScript is sync and async functionality depends on your functions implementation.
It has an event loop and it executes synchronously but whenever it will get the async function( the function which takes callback i.e setTimeout ,fs.readFile() etc) which is not the part of the javaScript then,
It put the function into the queue and invoke the queue function after all the native code(which is in current scope) execute then it pop the queue and invoke the functions.
and setTimeout explicitly set up an asynchronously timed callback to the function.
check this javaScript Async behavior ;
Here is my code
var x = 0
data.results[0].taxonomies.some(function(e){
if(taxo.indexOf(e.code)!=-1){ //if at least one code from the data base is in my list of codes
callback(validLic(data.results[0].taxonomies)) //return true after some other validations
return true
}else{
x++
return false
}
})
if(x==data.results[0].taxonomies.length){callback(false)}//if the entire array was processed, and I didn't find anything I was looking for, return false
I'd like someone to confirm that due the async nature of node, the last if statement is at some point, bound to fire off before I'm done processing the array.
How can I better manage this situation without the help of some sync or parallel library?
The reason I ask it that way is because I'm under the impression that if I can't write something to be completely async, then I'm not writing it efficiently, right?
EDIT:
Based on Luc Hendirks' logic, I have changed my code to this:
var flag = data.results[0].taxonomies.some(function(e){
if(taxo.indexOf(e.code)!=-1){ //if at least one code from the data base is in my list of codes
return true
}else{
return false
}
})
if(flag==true){
callback(validLic(data.results[0].taxonomies))
}else{
callback(false)
}
Because this follows the sync traits outlined below, I shouldn't have an issue with flag being undefined before the callback is called now right?
Javascript (and Node) are single threaded, meaning it has only 1 CPU available. If the functions you call only require CPU time, making it async is useless. If you need to call a function and the CPU has to wait (do nothing), then making it async is very useful. Because while it is waiting until the function is finished it can do something else.
A function that checks if a url is valid with a regular expression can be synchronous, as the CPU needs to do some calculations and you get the result. If the function actually does a GET request and checks the response code, the CPU has to wait until the response is received. In the meantime it could do something else, so this function should be made asynchronous.
The difference of a synchronous and asynchronous function is that a synchronous function returns a value:
function(a) { return a; }
and an asynchronous function returns the result using a callback function (this is an actual function that you put in as a function argument):
function(callback){
// Do something that takes time but not CPU, like an API call...
callback('Some result');
}
A synchronous function is called like this:
var a = something();
Asynchronous like this:
something(function(result){
console.log(result);
});
So to answer your question, if some() is an asynchronous function, then the last if statement can be executed before the some function is finished. Because: the CPU does not want to wait. It can do other stuff while waiting. That's the power of asynchronous programming. t
It is also important to know that "parallel" does not exist in Javascript/Node. There is only 'doing stuff instead of waiting', like executing multiple API calls at the same time. That is not parallel computing as in using multiple threads.
Here is some more info: What is the difference between synchronous and asynchronous programming (in node.js)
I'm a (relative) node newbie getting in the system, and all the enthusiasm in the community for "just write callbacks, everything's asynchronous and event driven, don't worry!" has left me a little confused as to the control flow within a single program (or in more node-ish terms, the control flow during the handling of a single request in a larger program)
If I have the following program running under node
var foo = function(){
console.log("Called Foo");
};
var bar = function(){
console.log("Called Bar");
};
var doTheThing = function(arg1, callback){
callback();
};
doTheThing(true, function() {
foo();
});
bar();
Is there any chance that foo will execute after bar? When I run the program via the command line locally, it's always
Called Foo
Called Bar
but I see so many warnings from well intended evangelists along the lines of don't assume your callback will be called when you think it will, that I'm unclear if they're just warning me about library implementation details, or if node.js does something weird/special when you use a function object as parameter.
No, there's no chance. Not for that code.
If you're writing your own functions, or if you have access to the code, you don't need to assume, you know whether everything's synchronous or otherwise, but if you don't have access to the code, or haven't yet read it, then no, you can't assume callbacks are going to be synchronous.
It's however bad practice to make assumptions like that for two reasons, first is that just because it's synchronous now doesn't mean somebody else, or forgetful future you can't change it later, and secondly, because if it's all synchronous, why are you/they using callbacks in the first place? The entire point of callbacks is to allow for the possibility of asynchronous calls. Using callbacks and then acting like they're always going to be synchronous, even if you know that's the case, makes your code confusing for anybody else coming in.
No
Your sample code is 100% synchronous, single-threaded, simple top-to-bottom. But that's because you don't do any I/O, don't have any real asynchronous calls, and don't use process.nextTick, setTimeout, or setInterval. To more realistically simulate async calls do something like:
function fakeAsync(name, callback) {
setTimeout(function () {
callback(null, name);
}, Math.random() * 5000);
}
function logIt(error, result) {
console.log(result);
}
fakeAsync('one', logIt);
fakeAsync('two', logIt);
fakeAsync('three', logIt);
Run that a few times and you'll see out-of-order results sometimes.
Is there any chance that foo will execute after bar?
In your current code, no. Although your doTheThing function has an asynchronous function signature (i.e. it takes a callback as the last argument, which to an outsider with no knowledge about the function's implementation would suggest that it's asynchronous), it's actually fully synchronous, and callback will be called without yielding to the runtime.
However
You really have no reason to give your doTheThing code an asynchronous signature, unless you're accommodating for introducing real async behavior into doTheThing at some point. And at that point, you have a problem, because the order in which foo and bar are called will flip.
In my opinion, there are only two good ways of writing code like you do: Either make it set in stone that doTheThing will be synchronous (most importantly: that it won't be dependent on I/O), which means that you can simply return from the function:
doTheThing = function(arg1){
return null
};
doTheThing()
foo()
bar()
or change the stub implementation of doTheThing directly to include a call to setImmediate, i.e.
var doTheThing = function(arg1, callback){
setImmediate(function() { callback(); );
};
Note that this can also be written as
var doTheThing = function(arg1, callback){
setImmediate(callback);
};
but that's just because at this moment, callback does not take any arguments. The first version is more close to what you had.
As soon as you do this, bar will always be called before foo, and it has now become safe to introduce async functionality into doTheThing.
I have 2 functions. The second one is faster than the first one,how could the function wait to complete first one's work?
function1(); // slow
function2(); // fast
JavaScript is imperative and single-threaded, it just works like this. function2() won't start until function1() finishes.
If by slow you mean calling asynchronously some external service via AJAX, then we're talking. function1() must provide some sort of callback so that when asynchronous request finishes, function2() is called:
function1(function2);
The implementation is trivial, e.g. using jQuery:
function function1(callback) {
$.ajax({url: 'some-url'}).done(callback);
}
If functions are to be called asynchronously, aside from the obvious callback approach, their sequencing could be based on the events framework. You could add an event listener with function1 as a handler, and trigger that event within function2.
You must be using some AJAX request. So, after ajax complete call callback function like:
function1 = new function(callback) {
$.ajax({...}).done(callback());
}
function1(function2);
If your calling one function after the other then it will finish the first either it may be slow or fast.