This paper addresses http://www.cnblogs.com/jasonxuli/p/5382090.html

Koajs Let the students who are used to blocking code writing feel very comfortable , No more building callback 了 , And there's no need to learn Promise Of then,catch These new things .

But actually ,Koajs This way of writing is a bit like the grammatical sugar of a language , It just puts yield It's packaged as Promise Chain call of . The library to do this is co Kuhe compose library ,compose Kuba koajs A bunch of Middleware in is refitted into function sets , and co These dolls were converted into Promise chain . Want to know Koajs Principle , I really need to know Promise Basic concepts of . This article assumes that you already know Promise Basic knowledge of .

koajs The usage of is like this :

var koa = require('koa')();

koa.use(function* m1(next){
     ...
     yield next;
     ...
}
 
koa.use(function* m2(next){
     ...
     yield next;
     ...
}
 
koa .listen(3000);
 
This koa.listen default callback yes koa Library application.js Medium app.callback, It's in this app.callback in , Called the key sentence :
var fn = this.experimental
? compose_es7(this.middleware)
: co.wrap(compose(this.middleware));
And that leads to co Kuhe compose Ku, these two koajs The core of the library .
 
First say compose library :
koa.use The key code of the function is this sentence  
this.middleware.push(fn);
That is to say this.middleware It's an array of middleware .
actually ,compose It's a [m1, m2, ...] It was converted into m1(m2(m3(...))), To facilitate co The next step of the library modification , as follows :
 
function compose(middleware){
  return function *(next){
    var i = middleware.length;
    var prev = next || noop();
    var curr;

    while (i--) {
      curr = middleware[i];            // curr = m3
      prev = curr.call(this, prev);   // m3.call(this, null)  >>> m3() namely prev=m3()
    }
 
    yield *prev;                             // m3()
  }
}
 
The final result is equivalent to the return of a function :m1(m2(m3))
 
This result serves as co Parameters of , What happened ?
 
co lib:
Actually, co convert yields to promise thens.
 
// fake codes
function co(gen){
     if gen is a function
          gen = gen();
    
     if gen is null || gen is not a function
          return resolve(gen);
 
onFulfilled();
 
      // onFulfilled() {
           try{
               var ret = gen.next();
          }catch(){
               reject(ret);
          }
next();
     }
    
     // next() {
          if ret.done == true
               return resolve(ret);
 
               // toPromise(){
               if ret is a general value
                    return resove(ret)
                if ret is a generator   // Extend by depth : Handle yield* 
                    return co(ret)
               }
 
           if (isPromise(value))
               return value.then(onFulfilled, onRejected);    // Extend by breadth : Deal with the next yield
     }
}
 
This paragraph co The code removes a lot of details that seem a little more complicated , It's helpful to clear the context .
 
See through co Kuhe compose library , You will know ,koajs It's just for you to write in synchronous blocking mode IO Freedom to deal with , In fact, it's behind the scenes Promise Chain call mode .
I'm just beginning to understand koajs When , The biggest question is this : Why can an asynchronous non blocking language deal with asynchronous in a blocking way IO Well ?
Now that's the answer .
 
2015-11-16 On Evernote
 
 
 

Koajs More articles on the principles

  1. 【Node.js】 bodyparser Implementation principle analysis

    Why do we need body-parser Maybe you and bodyparser Meeting is using Koa Frame time . When we try to send it from a browser POST When obtaining the request message entity in the request , This is the time , We want to , This from Koa since ...

  2. Handwriting koa-static Source code , Deep understanding of static server principles

    This article continues with the previous Koa Source series , There are already two articles in this series : The first one explains Koa Core architecture and source code : Handwriting Koa.js Source code The second one explains it @koa/router Architecture and source code : Handwriting @koa/router Source code ...

  3. Singular value decomposition (SVD) Principle and application in dimension reduction

    Singular value decomposition (Singular Value Decomposition, hereinafter referred to as SVD) It is a widely used algorithm in the field of machine learning , It can not only be used for feature decomposition in dimensionality reduction algorithms , It can also be used in recommendation systems , And natural language processing . yes ...

  4. node.js Study ( 3、 ... and ) ordinary node Program && Simple use of modules &&commonJS standard && Deep understanding of module principles

    One . A simple node Program 1. Create a new one txt file 2. Modify suffix This will pop up after modification , Click on " yes " 3. function test.js Source file Use node.js After running . If there is no such path ...

  5. Linear discriminant analysis LDA Principle summary

    In principal component analysis (PCA) In principle summary , We're looking at dimension reduction algorithms PCA Made a summary . Here we're going to do linear discriminant analysis, another classical dimension reduction method (Linear Discriminant Analysis, hereinafter referred to as LDA) Make a summary . ...

  6. [ primary ] KVM Explore the principle of virtualization (1)— overview

    KVM Explore the principle of virtualization - overview label ( The blank space to separate ): KVM Let me write it out front Not covered in this article kvm and qemu Basic installation operation of , I hope readers have a certain KVM practical experience . At the same time, I hope to take this series of blogs , Can be right KVM Bottom ...

  7. H5 Single page gesture sliding screen switching principle

    H5 Single page gesture sliding screen switching is adopted HTML5 Touch event (Touch) and CSS3 Animation (Transform,Transition) To achieve , The effect is shown below , This paper briefly talks about its implementation principle and main ideas . 1. Realization principle ...

  8. .NET Core Middleware registration and pipeline construction (1)---- Registration and building principles

    .NET Core Middleware registration and pipeline construction (1)---- Registration and building principles 0x00 Problem generation The pipeline is .NET Core It's a very critical concept in , Many important components exist in the form of middleware , Including rights management . session management ...

  9. python automated testing (2)- Basic technology principle of automation

    python automated testing (2) Basic technology principle of automation 1    summary Mentioned in the previous article : The first skill of automation is to be able to   See the essence through the phenomenon  , Put it into practice IT At work   Viewing data through the interface . Master the above skills ...

Random recommendation

  1. asp.net mvc Multiple conditions + Paging query solution

    development environment vs2010 css:bootstrap js:jquery bootstrap paginator I just wanted to be mvc paging , But the general data display needs retrieval conditions , And there are many conditions , So it became ...

  2. Spring:No bean named 'beanScope' is defined

    Beginners Spring,“No bean named 'beanScope' is defined” This question bothered me for hours , After checking the data and finding no results , After rewriting the code several times, I found that the problem was that the configuration file could not be put in the package ... Put it on s ...

  3. 《ASP.NET1200 example 》 Statistics website visits source code

    void Application_Start(object sender, EventArgs e)     {        // Code that runs when the application starts         int count=0;  ...

  4. Java Web Access paths to resources in

    stay web Application , With “/” It starts with the absolute path , Don't to “/” It starts with a relative path .   On the server side , Absolute paths are usually used . for example web.xml.struts.xml.servlet And so on “/” Start . service ...

  5. js Array sorting in

    js Array bubble sort , The principle and implementation of quick sort   Bubble sort : Compare any one digit in the array with the next , If you want to sort from small to large , Then put the little one in the front , Put the big ones in the back , Simply put, it's about swapping their positions , So repeatedly swapping bits ...

  6. jq event

    1,ready: When DOM Load ready to query and manipulate when bound to a function to be executed , Make sure that before using body Elemental onload event ,, There are no registered functions , Otherwise it will not trigger ready function . $(document).ready ...

  7. JNI With the underlying call

    Cross compilation Under one platform , Compile binary code that another platform can execute platform :windows,mac os,linux processor :x86,arm,mips The principle of cross compiling Source code -> compile -> link -& ...

  8. AT2442 フェーン Phenomenon (Foehn Phenomena)

    Title address Original address Answer key It's actually an interval plus , Single point query problem Of course, line segment trees / The tree array does , However, these two practices need to be discussed by category, so there will be more code Let's consider a simpler approach Difference ! Because the temperature is only related to the altitude difference , It's equivalent to ...

  9. Get along well with X-CTR100 l STM32F4 l MPU6050 Accelerometer gyroscope sensors

    I make wheels , You make cars , Makers build it together ! Tucker innovation news [ Tuck community www.xtark.cn ][ Tucker blog www.cnblogs.com/xtark/ ]      In this paper, X-CTR100 controller Onboard acceleration ...

  10. FreeMarker Dealing with variables that don't exist

    FreeMarker You can't tolerate references to variables that don't exist , Unless it's explicitly told what to do when the variable doesn't exist . Here are two typical treatment methods . A variable that doesn't exist and a variable that is null The variable of , about FreeMarker It's the same for me . Handle ...