The other day, I wrote this function in JavaScript as a simple DTO for an object from a jQuery plugin. I assumed that if I wrote a general return gridColumns line at the end of the function, the array could possibly be returned before my for loop was finished populating it. So I wrote this while (true) statement at the end, thinking I was being clever.
function getGridColumns() {
var gridColumns = [];
var records = $("#jqxGrid").jqxGrid("columns").records;
for (var i = 0; i < (records.length); i++) {
var obj = {
datafield: records[i].datafield,
width: records[i].width,
cellsalign: records[i].cellsalign,
hidden: records[i].hidden
}
gridColumns.push(obj);
}
while (true) {
if (gridColumns.length == records.length {
return gridColumns;
}
}
};
A buddy of mine looked at my little "hack" and said it was completely unnecessary, and I did some testing and determined that he's right.
So, here's where I'm at. How is JavaScript asynchronous, and how is it not? Can anyone help me understand this paradigm so that I can write better JavaScript?
-
3It's asynchronous when you make a function call to an asynchronous service. Nothing in your code above fits that description.Pointy– Pointy2015年10月12日 13:58:42 +00:00Commented Oct 12, 2015 at 13:58
-
@Pointy so async has to be explicitly defined, otherwise JavaScript will execute synchronously?Jacob Stamm– Jacob Stamm2015年10月12日 13:59:59 +00:00Commented Oct 12, 2015 at 13:59
-
And thanks for the downvote, whoever did that. Really constructive for people looking to learn, like myself.Jacob Stamm– Jacob Stamm2015年10月12日 14:01:56 +00:00Commented Oct 12, 2015 at 14:01
-
1Yes, normal JavaScript code executes synchronously. Services provided by the platform (web browser or Node, for example) may be asynchronous, and when that's the case there will be some way to pass a callback that will be invoked when the service operation completes. It's never a good idea to introduce a "busy wait" loop as in your code above.Pointy– Pointy2015年10月12日 14:05:26 +00:00Commented Oct 12, 2015 at 14:05
1 Answer 1
The most common mechanisms that spawn new "threads" of execution and thus so to speak introduce an asynchronous situation in javascript are AJAX call callbacks (unless the call was specifically made synchrounous) and setInterval() and setTimeout() calls. As pointed out by Pointy, there are more than this though.
3 Comments
Explore related questions
See similar questions with these tags.