Writing code like writing, how to rewrite asynchronous form to synchronous form
Is it a particular headache to write code with a bunch of indents and flower brackets? Why is there so much punctuation and all sorts of technical concepts? Can you write as freely as you write? Formally, the code is more formatted than the article, and the format represents the corresponding Technical principle . The text shares an article about "the Synchronous, asynchronous, blocking, non-blocking The technical concepts of the "A" and "B" are combined withJavascript in Image Loading, describes how to rewrite the asynchronous form to a synchronous form and write our code more elegantly.
def CodeFun( ):
Let's start with a story like this.
Leader M needs to prepare a PowerPoint presentation for the year-end summary that
He assigned the matter to his subordinate L
Story 1
Leader M is very uneasy about L.
So decided to stay by L's side and finish the PPT with him
Technical principle:: "Synchronous blocking
Aside:. This leader is so inefficient, can't he do it himself?
Story 2
After M arranged for L to do the PPT, the
running to the conference room for a meeting.
And from time to time go to subordinate L's workstation to see if the PPT is finished
Technical principle:: "Synchronous non-blocking
Aside:. This is what most leaders do (appear to be busy)
Story 3
M was explaining the PPT task when
Specific instructions to L.
Be proactive and come to him after you do the PPT.
But M is still unsure.
decided to wait on the L side of the
Do the PPT with him.
Technical principle:: "Asynchronous blocking
Aside:. It's worrying enough to have such a subordinate.
Story 4
M was explaining the PPT task when
Specific instructions to L.
Be proactive and come to him after you do the PPT.
At this time.
M decided to give full responsibility to L.
Continue the meeting by yourself in the conference room
Technical principle:: "Asynchronous non-blocking
Aside:. Subordinate L used his initiative to get the PPT done perfectly and leader M finished the meeting.
so-called synchronous asynchronous , only for L.
Silence after L's PPT, called "synchronization".
L is called "asynchronous" after doing the PPT and actively reporting.
In the case of "synchronization", M had to take the initiative to ask if the PPT was finished.
In the case of "asynchronous", M can go about his business and L will report back when he finishes the PPT.
so-called blocking non-blocking For M only.
In the case of "blocking", M accompanies L on the PPT.
In the "non-blocking" case, M goes to the meeting room.
Obviously, "asynchronous + non-blocking" is the most efficient.
This is the common understanding of the concepts of synchronous, asynchronous, blocking, and non-blocking. Going back to code writing, when we actually write code, we get more accustomed to a kind of linear thought " in a way that is somewhat similar to the process of doing a mathematical proof problem: the
Because the equilateral △ABC
So ∠A = ∠B = 60 degrees
and PE⊥AC
So ∠AEP is a right angle
So ∠APE = 30 degrees
In △PBQ
∠B = 60 degrees, ∠Q = 28 degrees
So ∠QPB = 92 degrees
So ∠EPD = 180 - 92 - 30 = 58 degrees
Line by line writing style, Very logical., Simple and clear cause and effect , This is a typical linear thought。 Here's one exampleJavascript examples of。 beginnerJS students, In order to draw the picture tocanvas above, It's usually written like this:
var img=..... .... ctx.drawImage(img,0,0);
When we were first learning, we were used to writing line by line, storing the image data in a variable img, and then calling the draw command to use img.
We can experiment in the console panel by opening Developer Tools in the browser.
var img=new Image(); img.src="https://images.unsplash.com/photo-1543363951-ec6198f35a38?auto=format&fit=crop&w=100&q=30"; var canvas=document.createElement("canvas"); var ctx=canvas.getContext("2d"); ctx.drawImage(img,0,0); document.body.innerHTML=''; document.body.appendChild(canvas);
Under runtime, if you follow the above writeup, the image will often not be drawn because the image is loaded "asynchronously". At this point, we need to rewrite the code to.
var img=new Image(); img.src="https://images.unsplash.com/photo-1543363951-ec6198f35a38?auto=format&fit=crop&w=100&q=30"; img.onload=function(){ var canvas=document.createElement("canvas"); var ctx=canvas.getContext("2d"); ctx.drawImage(img,0,0); document.body.innerHTML=''; document.body.appendChild(canvas); };
The code is starting to get indented and we need to understand the concept of 'scope' as we continue to write the image load as a function.
function loadImg(_url,_callback){ var img=new Image(); img.src=_url; img.onload=function(){ _callback(img); }; };
Load a picture of.
loadImg("http://xxxx",function(img){ ... });
What if it's multiple images loading?
loadImg("http://xx1",function(img){ loadImg("http://xx2",function(img){ loadImg("http://xx3",function(img){ loadImg("http://xx4",function(img){ ... }); }); }); });
A layer of nesting, written and looking very difficult?, To solve this problem, Promise came along and loadImg could be written then this way.
loadImg("http://xxx") .then(function(img){ .... });
Multiple images are loaded that look like this.
loadImg("http://xxx1") .then(function(img){ .... }); loadImg("http://xxx2") .then(function(img){ .... }); loadImg("http://xxx3") .then(function(img){ .... });
Is it starting to feel a bit like you're writing lines of code? But there's still an indent in the way. The real runnable code for the above example can be found as follows.
function loadImg(_url){ var img=new Image(); img.src=_url; return new Promise(function(resolve, reject){ img.onload=function(){ resolve(img); }; }); }; loadImg("https://images.unsplash.com/photo-1543363951-ec6198f35a38?auto=format&fit=crop&w=100&q=30") .then(function(img){ var canvas=document.createElement("canvas"); var ctx=canvas.getContext("2d"); ctx.drawImage(img,0,0); document.body.innerHTML=''; document.body.appendChild(canvas); });
Could that be more concise? Having a THEN following behind doesn't look too good either. And we're going after a line of writing. This is where async/await comes in, so let's rewrite it as follows
async function loadImg(_url){ var img=new Image(); img.src=_url; return new Promise(function(resolve, reject){ img.onload=function(){ resolve(img); }; }); }; var img=await loadImg('https://images.unsplash.com/photo-1543363951-ec6198f35a38?auto=format&fit=crop&w=100&q=30'); var canvas=document.createElement("canvas"); var ctx=canvas.getContext("2d"); ctx.drawImage(img,0,0); document.body.innerHTML=''; document.body.appendChild(canvas);
This loads the image and allows us to write in the familiar "line by line" style.
var img=await ... .... ctx.drawImage(img,0,0);
return Write code gracefully
About MIXLAB
MIXLAB Boundless Community is a future-oriented laboratory that promotes " Cross-border innovation, open for growth "The Idea.
—— Crossing Boundaries Openness Mutuality Learning Thinking Innovation.