I am an old hand in programming and recently returned to my old passion and try my best to fit into this object-oriented, event-driven vibrant new world, and although I see the benefits of unclassified Javascript behavior, there is a time when it really hinders simplicity and reusability . A simple example I was working on was to take a snapshot (mobile phone programmed in javascript, HTML, phonegap, ...), resize it and upload it to the website. Perfect sequence:
- Take a picture
- Upload photo to img element
- Resize image (using Pixastic)
- Upload it to the website
- Inform user about success error
All this would be a very simple sequential program if each step would return control to the next when it is finished, but in fact:
- Make the photo asynchronous, so the program tries to load it into the img element before it exists
- Upload the photo asynchronously so that the resize image starts before img is fully loaded.
- Resizing is asynchronous, so uploading to a website starts before the image is fully resized.
- Upload to the website - asyn so that the program continues until the photo is fully downloaded.
And btw 4 out of 5 steps include callback functions.
My solution this way is to put every step in the previous one and use .onload and other similar tricks. It looks something like this:
takeAPhoto(takeaphotocallback(photo) { photo.onload = function () { resizePhoto(photo, resizePhotoCallback(photo) { uploadPhoto(photo, uploadPhotoCallback(status) { informUserOnOutcome(); }); }); }; loadPhoto(photo); });
(I hope I haven’t made too many mistakes by introducing code into this, which is real, just too distracting)
I think this is a great example, where async is not good, and synchronization is good, because contrary to the processing of Ui events, we should have every step before the next one is executed, but the code is a Russian doll, it confuses and unreadable, reuse The code is difficult to achieve because of all the nesting, it is simply difficult to bring all the necessary parameters to the internal function without passing them to each container in turn or using evil global variables, and I would love that the result of all this code will give me a return code, but not vy container will be completed well before the return code will be available.
Now, to get back to Tom’s first question, what would be smart, easy to read and easy reuse of what would be a very simple program 15 years ago using let say C and a dumb electronic board?
The requirement is actually so simple that I have the impression that I should miss the fundamental understanding of Javsascript and modern programming. Of course, is technology designed to increase labor productivity?
Thank you for your patience
Raymond Dinosaur; -)