promise's past and future life

Keywords: JQuery JSON

problem

  • What is single thread and what is the relationship between asynchrony
  • What is event-loop
  • Have you ever used deferred in jquery
  • Basic Use and Principles of Promise
  • Introduce async/await (links and differences with Proise) - not a replacement, but a complement
  • Introduce an asynchronous solution

Single thread and asynchronism

Single-threaded, can only do one thing at a time, can avoid DOM rendering conflict.

  • Browsers need to render DOM, JS can modify the DOM structure, so when JS executes, browser DOM rendering pauses, and both JS can not execute at the same time.
  • Although web worker supports multiple threads, it cannot access DOM.

The solution is asynchronous. But there are problems with asynchrony.

  • Not in accordance with the written way, poor readability
  • Callback functions are not easy to modularize.

event loop

(221) What is event polling

Synchronize the code and execute it directly. Asynchronous function completion is first placed in the asynchronous queue. When the synchronization function is finished, the function of the asynchronous queue is polled.

Deferred of jQuery

  • Changes in jQuery 1.5

    Before 1.5, ajax was written in the same function as the callback function and the execution function. It's not good-looking or reusable.

    var ajax = $.ajax({
        url: 'data.json',
        success: function() {
            console.log('success1');
            console.log('success2');
        },
        error: function() {
            console.log('error');
    	}
    })
    

    After 1.5: Separate the callback function and perform chain operation.

    var ajax = $.ajax('data.json');
    ajax.done(function() {
        console.log('success1');
    	})
    	.fail(function() {
        	console.log('error');
        })
    	.done(function() {
        console.log('success1');
    	})
    	.fail(function() {
        	console.log('error');
        })
    
    //Or the following
    //Much like Promise.
    var ajax = $.ajax('data.json')
    ajax.then(function() {
        	console.log('success1');
    	}, function() {
        	console.log('error1');
    	})
    	.then(function() {
        	cosole.log('sucess2');
    	}, function() {
        	console.log('error2');
    	})
    console.log(ajax); //Returns an XHR object
    

    However, it should be noted that:

    • Unable to change the nature of asynchrony and single threading
    • callback can only be written out
    • It's a grammatical sugar, but it decouples the code.
    • It embodies the principle of openness and closeness: openness to expansion and closeness to modification.
  • Use jquery Deferred.

    The original function:

    var wait = function() {
        var task = function () {
            console.log('Execution operation')};
        setTimeout(task, 2000);
    }
    wait();
    

    Using deferred:

    function waitHandle() {
        var dtd = $.Deferred();  //Create a dtd object
        var wait =  function() { 
        	var task = function (dtd) { 
            	console.log('Execution operation');
                dtd.resolve(); //Represents asynchronous task completion
                //dtd.reject()// / indicates that the asynchronous task failed
        	}
        	setTimeout(task, 2000);
            return dtd; //Returns dtd
    	}
        return wait(dtd); //dtd does some operations and goes back out
    }
    var w = waitHandle(); 
    w.then(function() {
        console.log('ok1');
    },function() {
        console.log('error1');
    }).then(function() {
        console.log('ok2');
    },function(){
        console.log('error2');
    })
    
    • There are two types of API s for dtd, with different intentions:

      The first category, dtd.resolve(), dtd.reject() - Actively executed functions

      The second category, dtd. then: dtd. done, dtd.fail -- passive listening functions

      These two categories should be separated, otherwise the consequences will be serious.

  • Preliminary introduction of Promise concept

    function waitHandle() {
        var dtd = $.Deferred();
        var wait =  function() {
        	var task = function (dtd) { 
            	console.log('Execution operation');
                dtd.resolve(); //Represents asynchronous task completion
                //dtd.reject()// / indicates that the asynchronous task failed
        	}
        	setTimeout(task, 2000);
            return dtd.promise(); //Returns dtd
    	}
        return wait(dtd); //The promise object is returned.
    }
    

    promise filters out the resolve and reject functions. Only listener methods can be invoked. So the outside can only monitor the success or failure, but can not decide the success or failure by themselves.

(_Have you used deferred in jquery?

  • Examples of changes to ajax in jQuery 1.5
  • Explains how to simply encapsulate, using deferred, and refers to the open and closed principle
  • Explain the difference between promise and deferred

Basic Use and Principles of Promise

  • Basic grammar

    function loadImg (src) {
        var promise = new Promise(function(resolve, reject) {
            var img = document.createElement('img');
            img.onload = function() {
                resolve(img)
            }
            img.onerror = function () {
                reject()
            }
        });
        return promise;
    }
    
    var src = 'https://tse1-mm.cn.bing.net/th?id=OET.21b8717f0e7047bfa6d8e6fc10d91692&w=135&h=272&c=7&rs=1&o=5&pid=1.9';
    var result = loadImg(src);
    result.then(function(img) {
        console.log(1, img.width);
        return img;
    }, function () {
        console.log('e1');
    }).then(function (img) {
        console.log('2', img.width);
    })
    
  • Exception capture (reject and error)

    function loadImg (src) {
        var promise = new Promise(function(resolve, reject) {
            var img = document.createElement('img');
            img.onload = function() {
                resolve(img)
            }
            img.onerror = function () {
                reject()
            }
        });
        return promise;
    }
    
    var src = '';
    var result = loadImg(src);
    result.then(function(img) {
        console.log(1, img.width);
        return img;
    }, function () {
        console.log('e1');
    }).catch(function) {
        console.log('Picture loading failed')
    }
    
  • Multiple series

    var src1 = '';
    var result1 = loadImg(src1);
    var src2 = '';
    var result2 = loadImg(src2);
    result1.then(function (img1) {
        console.log('First picture loading');
        return result2;
    }).then(function (img2) {
        console.log('The second picture is loaded.')})
    
  • Promise.all and Promise.race

    Promise.all accepts an array of promise objects. The next step should be carried out uniformly after all the implementation is completed.

    var src1 = '';
    var result1 = loadImg(src1);
    var src2 = '';
    var result2 = loadImg(src2);
    Promise.all([result1, result2]).then(function (datas) {
        comsole.log('all', datas[0]);
        comsole.log('all', datas[1]);
    })
    Promise.race([resutl1, result2]).then(function (data) {
        console.log('race', data);
    })
    
  • Promise standard

    • Any technology promotion needs a set of standards to support it.
    • Anything that does not conform to the standard will eventually be abandoned by users.
    • Don't challenge standards, don't make standards by yourself

    State change

    • Three states
    • Initial state: pending
    • Irreversible

    then

    • promise instance must implement then
    • The n must accept two parameters as parameters, one successful and one failed.
    • If the function in the then returns the promise instance, then the next then executes the instance. If there is no return, the next one is to execute the original promise instance.

async/await

  • The call back is just split up

  • async/await is the most direct synchronization

    const load = async function() {
        const result1 = await loadImg(src1);
        console.log(result1);
        const result1 = await loadImg(src1);
        console.log(result1);
    }
    
    • await must be used with async

    • await is followed by a promise instance

    • Using babel-polifill, compatible

(221) Introduction of async/await (links and differences with Proise) - not substitution, but complementation

Basic grammar. Promise was used, but there was no conflict with Proise. It's totally synchronous, and there's no callback function anymore. But still can not change the nature of JS single-threaded, asynchronous.

Posted by delassus on Sun, 15 Sep 2019 21:08:14 -0700