Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
As a beginner in Javascript, i was quite in shock to find out that there isn't any "wait" mechanism in javascript (i'm not considering timeout, you'll see why in a second), and if i want to deal with an asynchronous command i needed to use a callback. Pay attention to the fact that i put the wait in quotes, its because JS can't really wait, I just can't find a better word.
the mechanism of callbacks quickly turned for me to a chain of ugly callbacks that made my code much harder to read.
the problem begin when you have to force a synchronous order on a sequence of asynchronous command (those that ask for a callback), for example ajax commands.
consider this example:

1. here is what i considered a nice function:
function foo(){
   var result = "error";
   var key=getKey();
   if(verify(key)){
      var name=getName();
      if (verify(name)) {
          login(key,name);
           result = "ok";
       } 
    }
return result;
}


2. now what if getKey and getName needed a callback and getName have to be called only after we acquire the key?? this function should be broke into this:

function foo(){
getKey(callback);
}
 
function callback(key){
if verify(key){
getName(callback2);
}
 
function callback2(name){
if verify(name){
return "ok";
//....
}
}



you see how this simple "nice" method becomes ugly when callbacks are needed? and what if you have 20 or so functions that needed to be called sequentially and not only two?
you will need to write 20 functions and chain them with the callbacks...sweet mother of ugliness.

3.here is the same function, but lets say that we could introduce a new syntax that will do exactly the same as in (2), but will look like this:
when the interpreter sees the "wait" word, some magic will happen behind the scenes to create the exact same effect as the code in (2):
function foo(){
var result = "error";
wait var key=getKey();//no callback is being send within the call.
if(verify(key)){
   wait var name=getName();//again, no callback is being send within the call
   if (verify(name)) {
        login(key,name);
result = "ok";
} 
}
return result;
}




this is how things look like in most other languages, but as we already know, in JavaScript it is more problematic because JavaScript is a single threaded language.
there are some smart way to work around things like using a "state machine like" mechanism and Promises...but none of them is as simple as just waiting for the asynchronous call to return.
another way to work around things is to build a tool, just like the tools that format your code, that could take a code written in the format of (3) and produce a code that looks like (2). building this tool is actually quite easy.

and now for my question:
instead of building an external tool to do the work, why not just teaching the JS interpreter to do the work??
why not using the already existing mechanism of closure to introduce a new "wait" feature into javascript??
what i mean is that if you'll think about it, all we need to do is to inroduce a new syntax that will cause the javascript interpreter to use the next line as the handler for the current asynchronous call, just like "function" label tells the interpreter to consider the next line as the body of a function (not exactly, but you know what i mean). like this:

JavaScript
function foo(){
//wait is a new syntax proposal that will tell the interpreter to wait for the //asynchronous call to finish. behind the scenes "wait" could be implemented by //telling the interpreter to use the next line as the handler of this call,
//and use the function's scope as the closure to this "fake" handler.
//we also need to tell the interpreter to save the current stack.

wait bar=doSomethingAsnyc(value);   
doNextAsyncCommend(bar);                                  
}                               



so my questions:
1. what do you think about this proposal?
2. is it possible to implement it using only existing mechanism of the current js interpreter features?

let me clarify just one thing:
I'm not suggesting to make JS a multi-threaded language or something fancy..actually i don't want to change anything in the inner-working of JS. I'm trying to suggest a syntactic sugar only and i want to understand if it is possible to introduce it using only existing mechanisms.


I have an incomplete proposal on how to do this and i hope that with your help we could actually bring this proposal into a practical way to implement a wait mechanism without breaking any existing standard, and who knows, maybe we could be able to introduce the new mechanism into FireFox and actually make a change.

I don't know how JavaScript interpreters implement the stack but i can imagine a theoretical implementation (that sadly needs to introduce new features to the interpreter) like this:

1. when you see the word "wait" in the beginning of the line, run the command (in our example the call to doSomethingAsnyc(value)) but Behind the scenes, pass within the call a fake callable object so that we will not break any existing syntax while the asynchronous function will try to send back the results using: callback(result);
this fake callable will actually save the result on top of the stack when it will be ready.

2. when you get to the next line of code, save a pointer (more like a marker) to the current position in the stack(+1 to save space for the return value of the call). leave the function scope and continue to run.

3. when the fake callable object that we have passed within the call is being called (meaning that the asynchronous call is completed), jump the stack pointer to the marker and save the return value on top of the stack.

4. pop the return value into the variable that was after the wait (the "bar"), and continue to run until the end of the function scope.

5. when reaching the end of the function scope, use the same mechanism that already exist in js to finish handling of an event and continue from the same spot where we left.

so, what do you think??

UPDEATE2:
after a very long discussion in the comments i see that both of the professional users that tried to answer my question did not understand me right.
I don't know how to explain things better and the English is doing me a hard time, so please, if someone got my proposal right please try to explain to others what it is about. just put it as an answer and ill update my question with your explanation.
Posted
Updated 29-Sep-14 1:06am
v9
Comments
Sergey Alexandrovich Kryukov 28-Sep-14 13:42pm    
In brief: a very bad <scratch>proposal ides.
—SA
P.S.: I removed "proposal", replaced with idea". I think many confusions would be eliminated if you realized that there is no a proposal.
—SA
yno1 28-Sep-14 14:00pm    
lol...and not in a brief?
Sergey Alexandrovich Kryukov 28-Sep-14 15:09pm    
If I was ready to explain it all, I would post an answer, not comment.
First thing: are we talking about Javascript used in a browser? If so, the programming model does not encourage threading, because you Javascript should process a single HTTP response, and, after that, a set of user input events, one at a time. Now think: who wait could improve it? What thread are you going to hang? If a UI thread, it will make the UI hanging. Not UI thread? But you don't have threads in Javascript. Want to introduce them, too? But then why talking about "wait"? it could be a comprehensive set of thread synchronization primitives.

If you are talking about other uses of Javascript, the whole story may make some sense, but now, how to take care about the Web model of its use?

To me, it looks apparent that you did not work through many existing aspects of your proposal. Where did you get the whole idea of wait? When you learned it, did you also understand its background?

—SA
yno1 28-Sep-14 16:17pm    
please read my clarification (i edited the original post).
you completely misunderstood my question:(
Sergey Alexandrovich Kryukov 28-Sep-14 16:41pm    
I did. Anyway if you "don't want to change anything in the inner-working of JS", there is no a subject of discussion. It won't have "wait" then. Now, do you understand that by waiting you don't introduce any parallelism? I would say, you are suggesting to kill non-existing parallelism. Again, learn how threading works on the platforms where it certainly makes sense.

Note that your suggestion is only a question. This is not a suggestion, in this sense. If would be a suggestions of you explained how it can really work.

—SA

1 solution

After all the clarifications done in the comments and Solution 1, I decided to put a formal answer.

Based on these clarifications, I will assume: 1) you have create some Javascript work which really works; 2) it works in some Web browser; 3) despite of the words "asynchronous command" written in the body of the question, this code does not do anything asynchronous.

Some necessary notes: first, I wrote "assume", because the level of certainty of your formulation is concerned; and your posts look confusing to me in general. Second, the statement #3 is redundant, because if could be derived from #1: Javascript model is even-oriented and single-threaded, without asynchronous execution (except timer events, of course, which we don't need to take into account).

This way, we can approach it from a different side: in Javascript's model, as any single-threaded models (event-oriented, in particular), there are no waits, by definition. You never wait for anything; you just do the next call, and executions before it returns lasts as long as it lasts. As to the even-oriented design, it requires that it lasted for not too long time. All the execution is passed through one single event loop. When some condition is met, it can be taken into account on next iteration.

By the way, the developer should overcome the sequential thinking (even multi-threaded sequential thinking). Some think that such thinking is more natural, but in fact, this is just a matter of habit. Come to think about, all your problem lies there. What you have is the methodical mistake, and this mistake look very familiar to me. It can lead you to bad design, as Peter told you in his comment to his Solution 1 (and I tend to agree), or it could be wrong; and your design makes some sense — it doesn't really matter. Why? I'll try to explain in next paragraph.

Now, let come to the answer: as there is actually no wait, an attempt to introduce any API or reserved word containing the word "wait" would be misleading at best. Instead of proposing some language/technology feature, in this case, you need better to think at what you are really doing.

Finally, I would like to complete the discussion of the asynchronous behavior, even though it turns out to be irrelevant to the original question. Don't get me wrong: just because the browser can be considered as a whole platform, and Javascripts as application, I am sure that, theoretically speaking, asynchronous model is quite possible. And it can take the form of threads, otherwise there is no any "wait". I can imagine different asynchronous models though (look at TPL where the threads are abstracted). But the fact is: there are no development of Javascript in this direction; it remains fundamentally single-threaded. More importantly, browser and Web operation makes the standard very important; and the standard has no provision for parallelism. If we evolve in this direction, it will make the scripting language and client-side technology a fundamentally different technology.

—SA
 
Share this answer
 
Comments
yno1 29-Sep-14 4:10am    
I really appreciate your intentions and your time. really. so first of all let me thank you for that.
But sadly, you still misunderstood me. I blame no one but my bad English and maybe i should have not use the term asynchronous in my question.
let us wait and see if some other users could understand my question and hopefully explain it better then me.
As a last resort i also tried to explain to Kornfeld Eliyahu Peter the situation in my mother tongue and if he understand me i hope he could clear the thing that i couldn't.

Thanks again for your time!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900