美文网首页
Async学习(一)

Async学习(一)

作者: Sommouns | 来源:发表于2019-04-16 20:24 被阅读0次

    主要参考 You Don‘t JS

    引言

    // ajax(..) is some arbitrary Ajax function given by a library
    var data = ajax( "http://some.url.1" );
    console.log( data );
    // Oops! `data` generally won't have the Ajax results
    

    ajax请求通常无法马上返回,此时data中没有任何数据

    // ajax(..) is some arbitrary Ajax function given by a library
    ajax( "http://some.url.1", function myCallbackFunction(data){
      console.log( data ); // Yay, I gots me some `data`!
    } );
    

    Warning: You may have heard that it's possible to make synchronous Ajax requests. While that's technically true, youshould never, ever do it, under any circumstances, because it locks the browser UI (buttons, menus, scrolling, etc.) andprevents any user interaction whatsoever. This is a terrible idea, and should always be avoided.

    正文

    Async Console

    var a = {
      index: 1
    };
    // later
    console.log( a ); // ??
    // even later
    a.index++;
    

    console.log()是一个异步函数么?
    我的理解是 不是。console是并不是一个js官方提供的对象,各个浏览器都有自己提供的实现方案(包括node)。这段代码,是一种比较少见的情况,因为Chrome的Console是要在控制台打开才生效的。
    解决方法是做一个快照,字符串化,而不是变量

    JSON.stringify(..)
    

    Event Loop

    // `eventLoop` is an array that acts as a queue (first-in, first-out)
    var eventLoop = [];
    var event;
    
    // keep going "forever"
    while (true) {
        // perform a "tick"
        if (eventLoop.length > 0) {
            // get the next event in the queue
            event = eventLoop.shift();
            // now, execute the next event
            try {
                event();
            }
            catch (err) {
                reportError(err);
            }
        }
    }
    

    队列是先进先出,这也就解释了为什么setTimeout(func fn, 0)会最后执行了。

    Parallel Threading

    var a = 20;
    function foo() {
      a = a + 1;
    }
    function bar() {
      a = a * 2;
    }
    // ajax(..) is some arbitrary Ajax function given by a library
    ajax( "http://some.url.1", foo );
    ajax( "http://some.url.2", bar );
    

    并行和异步是完全两码事

    async is about the gap between now and later. But parallel is about things being able to occur simultaneously.
    就上面这段代码而言,如果是根据foo和bar的先后顺序,有可能是41或者42
    如果是多线程并行的话,Memory就会共享

    • Thread 1 ( X and Y are temporary memory locations):
    foo():
    a. load value of `a` in `X`
    b. store `1` in `Y`
    c. add `X` and `Y`, store result in `X`
    d. store value of `X` in `a`
    
    • Thread 2 ( X and Y are temporary memory locations):
    bar():
    a. load value of `a` in `X`
    b. store `2` in `Y`
    c. multiply `X` and `Y`, store result in `X`
    d. store value of `X` in `a
    

    由于Memory共享那么

    1a (load value of `a` in `X` ==> `20`)
    2a (load value of `a` in `X` ==> `20`)
    1b (store `1` in `Y` ==> `1`)
    2b (store `2` in `Y` ==> `2`)
    1c (add `X` and `Y`, store result in `X` ==> `22`)
    1d (store value of `X` in `a` ==> `22`)
    2c (multiply `X` and `Y`, store result in `X` ==> `44`)
    2d (store value of `X` in `a` ==> `44`)
    

    或者

    1a (load value of `a` in `X` ==> `20`)
    2a (load value of `a` in `X` ==> `20`)
    2b (store `2` in `Y` ==> `2`)
    1b (store `1` in `Y` ==> `1`)
    2c (multiply `X` and `Y`, store result in `X` ==> `20`)
    1c (add `X` and `Y`, store result in `X` ==> `21`)
    1d (store value of `X` in `a` ==> `21`)
    2d (store value of `X` in `a` ==> `21`)
    

    要通过一些操作来避免这个可怕的情况,比如互锁Memory,后端语言了解的不多。

    Job Queue

    总结一下,就是一个ES6中的新概念,主要就是针对Promise,优先级高于事件循环
    比如Promise和setTimeout(fn,0),promise的then会先执行

    Review

    A JavaScript program is (practically) always broken up into two or more chunks, where the first chunk runs now and the next chunk runs later, in response to an event. Even though the program is executed chunk-by-chunk, all of them share the same access to the program scope and state, so each modification to state is made on top of the previous state.

    Whenever there are events to run, the event loop runs until the queue is empty. Each iteration of the event loop is a "tick."User interaction, IO, and timers enqueue events on the event queue.

    At any given moment, only one event can be processed from the queue at a time. While an event is executing, it can directly or indirectly cause one or more subsequent events.

    Concurrency is when two or more chains of events interleave over time, such that from a high-level perspective, they appear to be running simultaneously (even though at any given moment only one event is being processed).

    It's often necessary to do some form of interaction coordination between these concurrent "processes" (as distinct from operating system processes), for instance to ensure ordering or to prevent "race conditions." These "processes" can alsocooperate by breaking themselves into smaller chunks and to allow other "process" interleaving.

    相关文章

      网友评论

          本文标题:Async学习(一)

          本文链接:https://www.haomeiwen.com/subject/gkwxwqtx.html