Asynchronous topics

Synchronous and asynchronous

/* 
    What is asynchronous synchronization: synchronous and asynchronous message is a notification mechanism
        Synchronous blocking:
            A calls B, B deal with the results obtained, before returning to A
            A In the process, the results have been waiting for B, before did not get the result, we need to A (caller) has been waiting call and confirm whether to return results, get the result and then continue again implemented.
            Do one thing, before did not get the result, we have been waiting for, wait until there are results, and then do the following things.
        Asynchronous non-blocking:
            A calls B, B without waiting for the results, via a state B, or A notification callback function to handle.
            Do one thing, do not wait for the results of things, and then went busy with anything else, with the result, and then be told by state B, or handled by the callback function.
        Life examples
            Xiao Ming go to the library to borrow books, and administrators say look for that book, a notebook administrators went to check, only to tell Xiao Ming after finishing up, there is no such book;
            A librarian B Xiaoming
            The investigation of this process takes time, so
            Synchronization -> found in the course administrator or can not be found, the notice will not go back Xiao Ming, Xiao Ming needs 'have' to ask him results
            Asynchronous -> After the administrator is found, 'Notify way' to tell Bob, so Bob can continue to do other things, waiting for a notification to inform the administrator on the line;
*/
{
    // Sync: blocking 
    function the Test () {
        console.log("test...");
    }
    test();
    console.log ( "End ..." );
     // code execution process: test ... -> end ... because they are carried out step by step down; 
}
{
    @ Asynchronous: nonblocking 
    // very typical asynchronous function in JS: timer 
    function Test () {
        setTimeout(()=>{
            console.log("test...")
        },1000)
    }
    test();
    the console.log ( "End ..." );
     // execution order -> Test End ... ... 
}
{
    // ? How to make test execution and then execute end it 
    // 1. Directly into the end of the test 
    // 2. callback callback; 
    function test (cd) {
        setTimeout(()=>{
            console.log("test...");
            cd && cd();
        },1000);
    }
    test(function(){
        console.log("end...");
    });
    // execution order -> Test End ... ... 
}

Asynchronous small case: box motion

Recursion

{
     Function Move (ELE, direction, target) { // element, the direction (left, top), the target point 
        the let = Start the parseInt (window.getComputedStyle (ELE, null ) [direction]); // (elements, pseudo-class) [style name]; -> Get current position of the element [has units]; 
        the let speed =. 5; // speed; 

        Start = Start + speed;
        ele.style [direction] = Start + "PX" ;
         // not listen to plus -> recursive (calls itself) 
        the setTimeout (() => {
             IF (Start === target) {
                console.log("停")
            } else {
                move(ele, direction, target);
            }
        }, 50);
    }
    move(box, 'left', 200)
}

Animation frames requestAnimationFrame

{
     // animation frames, with respect to the better performance setTimeout; 
    function Move (ELE, direction, target) {
         function Fn () {
            let start = parseInt(window.getComputedStyle(ele, null)[direction]);
            let speed = 5;

            start = start + speed;
            ele.style[direction] = start + "px";

            if (start == target) {
                console.log("停");
            } else {
                window.requestAnimationFrame(fn);
            }
        }
        fn();
    }
    move(box, 'left', 200)
}

Callback

{
     // How to move from the top to the bottom of it -> callback -> callback region also 
    function the Move (ELE, direction, target, cd) {
         function the Fn () {
            let start = parseInt(window.getComputedStyle(ele, null)[direction]);
            the dir the let = (target-Start) /Math.abs (target-Start); // Analyzing negative :( target point - the current position) in addition to the Math.abs (target point - the current position) -> 1 / -1
             // the console.log (10 / the Math.abs (10)); //. 1; 
            // the console.log (-10 / the Math.abs (-10)); // 0-1; 
            the let the dir * Speed =. 5; / / * get negative positive negative territory 

            Start = Start + Speed;
            ele.style[direction] = start + "px";

            if (start == target) {
                console.log("停");
                cd && cd();
            } else {
                window.requestAnimationFrame(fn);
            }
        }
        fn();
    }
    move(box,'left',200,function(){
        move(box,'top',200,function(){
            move(box,'left',0,function(){
                move(box,'top',0);
            })
        })
    });
}

Use promise Objects

{
    // promise
    function move(ele, direction, target) {
        return new Promise(resolve => {
            function fn() {
                let start = parseInt(window.getComputedStyle(ele, null)[direction]);
                let dir = (target - start) / Math.abs(target - start);
                Speed the let = the dir *. 5; // * It becomes negative in negative 

                Start = Start + Speed;
                ele.style[direction] = start + "px";

                if (start == target) {
                    // console.log("停");
                    resolve("停");
                } else {
                    window.requestAnimationFrame(fn);
                }
            }
            fn();
        });
    }
    move(box,'left',200).then(res=>{
        return move(box,'top',200);
    }).then(res=>{
        return move(box,'left',0);
    }).then(res=>{
        return move(box,'top',0);
    }).then(res=>{
        console.log(res);
    })
}

Using async and await

{
    // async和await
    function move(ele, direction, target) {
        return new Promise(resolve => {
            function fn() {
                let start = parseInt(window.getComputedStyle(ele, null)[direction]);
                let dir = (target - start) / Math.abs(target - start);
                Speed the let = the dir *. 5; // * It becomes negative in negative 

                Start = Start + Speed;
                ele.style[direction] = start + "px";

                if (start == target) {
                    // console.log("停");
                    resolve("停");
                } else {
                    window.requestAnimationFrame(fn);
                }
            }
            fn();
        });
    }
    async function queue() {
        try {
            await move(box, 'left', 200);
            await move(box, 'top', 200);
            await move(box, 'left', 0);
            await move(box, 'top', 0);
            console.log ( "All is finished" );
        } The catch (ERR) {
             // reception error; 
            the console.log (ERR);
        }
    }
    queue();
}

requestAnimationFrame and setTimerout performance competition

{
    function fn(){
        document.title ++;
        setTimeout(()=>{
            fn();
        },1000);
    }
    // fn();
}
{
    function fn(){
        document.title ++;
        window.requestAnimationFrame (the Fn); // jump to another browser stopped. 
    }
    fn();
}

Object promise

{
    /* 
        Promise object is a class already defined;
            Three states: pending, resolve, reject
    * / 
    The let P1 = new new Promise ((Resolve, Reject) => {
         // nothing Write Back -> Pending value = "undefined" 
        // Resolve (111); // Resolve value = "111" -> in Firefox also known as: fulfilled successfully 
        // Reject ( "error"); // failed -> error 

        the setTimeout (() => {
            Resolve ( "success" );
             // Reject ( "wrong"); 
        }, 1000 );
    });
    // console.log(p1);

    // the then -> is successfully resolve 
    // the then two parameters; onresolve, onreject 
    / * p1.then ((RES) => {
        console.log(res);
    },(error)=>{
        console.log(error);
    }); */
    /* p1.then((res)=>{
        console.log(res);
    }). One way to catch (err => {// an error process is
        console.log(err);
    }) */

    // the then: three kinds of return; 
    {
         // 1. there is no return of the callback: automatically returned objects promise; 
        / * the let reslut p1.then = ((RES) => {
            console.log(res);
        });
        console.log(reslut); */

        // 2. the callback return: return automatically by the packaging promise value, and then return the object promise; 
        / * the let reslut1 p1.then = ((RES) => {
            console.log(res);
            return "some value";
        });
        // So here we can continue then;
        reslut1.then((res)=>{
            console.log(res);//some value;
        })
        console.log(reslut1); */

        // 3. The return of the object a promise: then will return this promise; 
        the let reslut2 p1.then = ((RES) => {
             return  new new Promise ((Resolve) => {
                Resolve ( "the return of Promise" );
            });
        });
        console.log(reslut2);
    }
}

promise Load picture small case

{
    function loadImg() {
        return new Promise((resolve, reject) => {
            let img = new Image();
            img.src = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=102864642,3880374403&fm=11&gp=0.jpg";
            img.onload = function () {
                 // the console.log ( "loaded"); 
                Resolve ( "image is loaded" );
                document.querySelector("body").appendChild(img);
            }
            img.onerror = function(){
                Reject ( "image loading failed" );
            }
        });
    }
    loadImg().then(res=>{
        console.log(res);
    },err=>{
        console.log(err);
    });
}

 async和await

// ES7 syntax: async and the await; 
{
    let p1 = new Promise(resolve => {
        setTimeout(() => {
            Resolve ( "executed successfully" )
        }, 1000)
    })
    let p2 = new Promise(resolve => {
        setTimeout(function () {
            Resolve ( "the successful implementation of 222" )
        }, 2000)
    });
    // executing the execution p1 and P2 
    {
         // p1.then (RES => { 
        //      the console.log (RES); 
        //      return P2; 
        // }). The then (RES => { 
        //      the console.log ( RES); 
        //      the console.log ( "were completed"); 
        // }); 
    }

    {
        // asynchronous functions become synchronized with the writing 
        / * 
            1.async and await to appear together
            If a subject must 2.await promise;
        */
        async function fn() {
            let res1 = await p1;
            console.log(res1);
            let res2 = await p2;
            console.log(res2);
            console.log ( "all finished" )
        }
        fn();
    }
}

 Promise function

{
     // Promise resolve it is an object of the static method 
    // the let Promise.resolve RES = (); 
    // the console.log (RES); // can get a promise resolve 
    // the let Promise.reject RES1 = ( ); 
    // the console.log (RES1); // promise Reject state objects; 

    the let P1 = new new Promise ((Resolve, Reject) => {
        setTimeout(()=>{
            console.log(111);
            resolve(111);
        },2000);
    });
    let p2 = new Promise((resolve,reject)=>{
        setTimeout(()=>{
            console.log(222);
            resolve(222);
            // reject("error");
        },1000);
    });
    let p3 = new Promise((resolve,reject)=>{
        setTimeout(()=>{
            console.log(333);
            resolve(333);
        },3000);
    });
    @ Premise: all promise to be successful; 
    // All the successful results into an array; 
    // Promise.all ([P1, P2, P3]) the then (RES => {. 
    //      the console.log (RES ); 
    // });

    // get the fastest execution 
    Promise.race ([P1, P2, P3]). The then (RES => {
        console.log(res);
    });
}

 

Guess you like

Origin www.cnblogs.com/Afanadmin/p/12400293.html