The front-end advanced interview asks questions about asynchrony

When it comes to asynchron, you may think of event-loop Promise Async/Await, etc. Let’s talk about these questions:

  • What is single threading and what does asynchrony have to do with it
  • What is the event – loop
  • At present, what is the solution of ASYNCHRONOUS JS
  • How to solve asynchrony using jquery
  • Promise standard
  • The use of async/await

What is single threading and what does asynchrony have to do with it

  1. Single thread – Only one single thread can do one thing (code demo)
// JS execution and DOM rendering temporarily stalled during the loop
var i, sum = 0;
for (i = 0; i < 100000000; i++) {
    sum += i;
}
console.log(sum);

// Alert is not handled, JS execution and DOM rendering are temporarily stalled
console.log(1);
alert('hello');
console.log(2)
Copy the code
  1. Reason – Avoid DOM rendering conflicts
  • The browser needs to render the DOM
  • JS can modify the DOM structure
  • The browser DOM will not render temporarily while JS executes
  • Two pieces of JAVASCRIPT code cannot be executed at the same time.
  • Webworder supports multithreading, but does not have DOM access
  1. Solution — Asynchronous (code demo)
console.log(100)
setTimeout(function () { 
   console.log(200)           // Execute after 1000ms anyway
},1000)                         // Let the rest of the JS code run
console.log(300)
console.log(400)
Copy the code
console.log(100)
$.ajax({
    url:'xxx'.success: function (result) {     // Wait until ajax loads
        console.log(result)         // Let the rest of the JS code run}})console.log(300)
console.log(400)
Copy the code

Problems with asynchrony

Problem 2: Callback is not easily modularizedCopy the code

Answer to questions:

1. Single thread means that only one thing can be done and two js segments cannot be executed at the same time. 2. Asynchrony is a helpless solution, although there are many problemsCopy the code

What is the event – loop

Knowledge concatenation: 1. Single thread - can only do one thing at a time 2. Reasons to avoid DOM rendering conflicts 3. Solution: Asynchronous 4. Implementation mode: Event-loopCopy the code

Text interpretation

  • Event polling, JS asynchronous implementation of the specific scheme
  • Synchronize code, synchronize execution
  • Asynchronous functions are first placed in asynchronous queues
  • After the synchronization function completes, the polling performs the asynchronous queue function

The example analysis

The first:

    setTimeout(function () {
        console.log(100)})console.log(200)
Copy the code

The second:

    setTimeout(function () {
        console.log(1)},100)
    setTimeout(function () {
        console.log(2)})console.log(3)
Copy the code

The third:

    $.ajax({
        url: 'xxxx'.success : function (result) {
            console.log('a')
        }
    })
    setTimeout(function () {
        console.log('b')},100)
    setTimeout(function () {
        console.log('c')})console.log('d')
Copy the code

Problem solving

1. Event polling, JS asynchronous solution 2. What is asynchronous queue, when to put into the asynchronous pair column 3. The process of pollingCopy the code

At present, what is the solution of ASYNCHRONOUS JS

1.jQuery deferred
2.Promise
3.Async/Await
4.Generator
Copy the code

How to solve asynchrony using jquery

  • Has jquery Deferred been used

    1. Changes to jquery 1.5
    • Jquery 1.5 changes – before 1.5

          var ajax = $.ajax({
              url:'XXX'.success: function () {
                  console.log('success1')
                  console.log('success2')
                  console.log('success3')},error: function () {
                  console.log('error')}})console.log(ajax) // Return an XHR object
      Copy the code
    • Jquery 1.5 changes – since 1.5

      var ajax = $.ajax('xxxx');
      ajax.done(function () {
          console.log('success1')
      }).fail(function () {
          console.log('error')
      }).done(function () {
          console.log('success2')})console.log(ajax)  // Returns a Deferred object
      Copy the code
      // Very much like Promise
      var ajax = $.ajax('xxx')
      ajax.then(function () {
          console.log('success 1')},function () {
          console.log('error 1')
      }).then(function () {
          console.log('success 2')},function () {
          console.log('error 2')})Copy the code

    Answer to questions:

    Callback is the only form that can be written without changing the asynchronous and single threaded nature of JS. It is a syntactic sugar form, but decouples the code. 4Copy the code
    1. Using jQuery Deferred
        // Give a simple asynchronous operation using the setTimeout function
        var wait = function () {
            var tast = function () {
                console.log('Execution completed')
            }
            setTimeout(tast, 2000)
        }
        wait()
        // New requirement: To perform some particularly complex operation after execution, the code may be many and divided into several steps
    Copy the code
        function waitHandle () {
            var dtd = $.Deferred() // Create a Deferred object
            
            var wait = function (dtd) {  // Request that a Deferred object be passed in
                var tast = function () {
                    console.log('Execution completed')
                    dtd.resolve()       // Indicates that the asynchronous task is complete
                    // DTd.reject () // indicates asynchronous task failure or error
                }
                setTimeout(tast, 2000)
                return dtd
            }
            // Note that there must be a return value
            return wait(dtd)
        }
        
        var w = waitHandle()
        w.then(function () {
            console.log('ok 1')},function () {
            console.log('error 1')
        }).then(function () {
            console.log('ok 2')},function () {
            console.log('error 2')})// And dtd.done dtd.fail
    Copy the code

    Answer to questions:

    DTD. Resolve DTD. Reject 3. Dtd.then DTD.done DTD.fail 4. These two classes should be separated, otherwise the consequences will be severe. 5. Try consequence 6 by executing DTD.reject () at the end of the code above. Use a DTD. PromiseCopy the code
        function waitHandle () {
            var dtd = $.Deferred()
            var wait = function (dtd) {
                var tast = function () {
                    console.log('Execution completed')
                    dtd.reject()
                }
                setTimeout(tast, 2000)
                return dtd.Promise() // Note that we return a Promise, not a Deferred object
            }
            return wait(dtd)
        }    
        
    Copy the code
        var w = waitHandle()  // After the above changes, w receives a Promise object
        $.when(w)
            .then(function () {
                console.log('task 1')
            })
            .then(function () {
                console.log('task 2')})// w.ject () // An error is reported when executing this
    Copy the code

    3. Initially introduce the Promise concept

    Answer to questions:

    2. Show how to simplify the encapsulation by using Deferred 3. Explain the difference between a Promise and a DeferredCopy the code

The standard of Promise

Basic use and principles of Promise

  • A review of basic grammar
function loadImg (src) {
    const promise = new Promise(function (resolve, reject) {
        var img = document.createElement('img')
        img.onload = function () {
            resovle(img)
        }
        img.onerror = function () {
            reject()
        }
        img.src = src
    })
    return promise
}

var src = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583670709077&di=30593978e23e2d1c6830cbdd7d2bdd18&i mgtype=0&src=http%3A%2F%2Fwww.piaodown.com%2Fupload%2F20187%2F2018072626027685.png'
var result = loadImg(src)

result.then(function (img) {
    console.log(img.width)
},function () {
    console.log('failed')
}).then(function (img) {
    console.log(img.height)
})

Copy the code
  • Exception handling
// Then can accept only one parameter, and finally catch is used
result.then(function (img) {
    console.log(img.width)
}).then(function (img) {
    console.log(img.hieght)
}).catch(function (ex) {
    // Catch
    console.log(ex)
})
Copy the code
  • Several series
var src1 = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583670709077&di=30593978e23e2d1c6830cbdd7d2bdd18&i mgtype=0&src=http%3A%2F%2Fwww.piaodown.com%2Fupload%2F20187%2F2018072626027685.png'
var result1 = loadImg(src1)
var src2 = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583739408720&di=71d5005f34a42c7ee37e05e4f48f4c83&i mgtype=0&src=http%3A%2F%2Fa3.att.hudong.com%2F68%2F61%2F300000839764127060614318218_950.jpg'
var result2 = loadImg(src2)

result1.then(function (img) {
    console.log('First picture', img.width)
    return result2
}).then(function (img) {
    console.log('Second picture', img.height)
}).catch(function (ex) {
    console.log(ex)
})


Copy the code
  • Promise. All and Promise. Race
All receives an array of Promise objects
// Execute success
Promise.all([result1, result2]).then(datas= > {
// Receive data is an array containing the contents returned by multiple Promises in turn
    console.log(datas[0])
    console.log(datas[1])})// promise. race receives an array of Promise objects
// Execute success as long as there is one completion
Promise.race([result1, result2]).then(data= > {
// Data is the value of the first fulfilled Promise
    console.log(data)
})

Copy the code
  • Promise standard

    1. Gossip about “standards.

    - Any technology promotion needs to use a set of standards to support - such as HTML, JS, CSS, HTTP and so on, no rules and no standards - anything that does not meet the standards will be abandoned by users - do not challenge standards, do not create standardsCopy the code

    2. State changes

    - There are three states: Pending depressing - The initial state is pending which becomes depressing; or pending which becomes reject - the state change is irreversibleCopy the code

    3.then

    - Then () must accept two function arguments. - Then () must return a Promise instanceCopy the code

    Example code:

    var result = loadImg(src)
    result.then(function (img) {
        console.log(img.width)
    },function () {
        console.log('failed')
    }).then(function (img) {
        console.log(img.height)
    })
    Copy the code
    result1.then(function (img) {
        console.log('First image loaded')
        return result2
    }).then(function (img) {
        console.log('Second image loaded')})Copy the code

Answer to questions:

  • The basic grammar
  • How to catch exceptions
  • Benefits of multiple series-chain executions
  • Promise. Race and Promise. All
  • Criteria for Promise – state changes,then functions

The use of async/await

  • Then simply splits the callback
var w = waitHandle()
w.then(function () {
    console.log('ok 1')},function () {
    console.log('err 1')
}).then(function () {
    console.log('ok 2')},function () {
    console.log('err 1')})Copy the code
  • Async /await is the most direct way to write async/await
const load = async function () {
    const result1 = await loadImg(src1)
    console.log(result1)
    const resutl2 = await loadImg(src2)
    console.log(result2)
}
load()
Copy the code
  • grammar

    1. To use await, functions must be identified with async

    2. Await followed by an instance of Promise

    3. The need for Babel – polyfill

    function loadImg () {
        var promise = new Promise(function (resolve, reject) {
            var img = document.createElement('img')
            img.onload = function () {
                resovle(img)
            }
            img.onerrror = function () {
                reject()
            }
            img.src = img
        })
        return promise
    }
    
    var src1 = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583670709077&di=30593978e23e2d1c6830cbdd7d2bdd18&i mgtype=0&src=http%3A%2F%2Fwww.piaodown.com%2Fupload%2F20187%2F2018072626027685.png'
    var src2 = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583739408720&di=71d5005f34a42c7ee37e05e4f48f4c83&i mgtype=0&src=http%3A%2F%2Fa3.att.hudong.com%2F68%2F61%2F300000839764127060614318218_950.jpg'
     
    const load = async function () {
        const result1 = await loadImg(src1)
        consoel.log(result1)
        const result2 = await loadImg(src2)
        console.log(result2)
    }
    load()
    
Copy the code

Answer to questions:

[A]. [B]. [C]. Completely synchronous writing method, no callback function d. but does not change JS single thread, asynchronous natureCopy the code

Conclusion: The above is about the current asynchronous solution, if you think the article is good, I hope you can give a thumb-up to the article of little 🐟, I hope to bring help to more interviewers, thank you!