Asynchronous and single-threaded interview questions

Asynchronous and single threaded

  • topic
  • Knowledge points
  • answer

topic

  • What is the difference between synchronous and asynchronous?
  • Handwritten promise to connect to a picture
  • What are the asynchronous scenarios used in the front-end?
    Insert picture description here

Knowledge points

  • Single thread and asynchronous
  • Application scenarios
  • callback hell 和 Peomise

Single thread and asynchronous

  • JS is a single-threaded language and can only do one thing at the same time
  • Browser and nodejs to support JS startup process, such as Web Worker
  • JS and DOM rendering share the same thread, because JS can modify the DOM structure
  • Can't get stuck when encountering waiting (network request, timing task)
  • Need to be asynchronous
  • Destroy the callback function form

Insert picture description here

Asynchronous and synchronous

  • Based on JS is a single-threaded language
  • Asynchrony does not block code execution
  • Synchronization will block code execution

Application scenarios

  • Network request, such as ajax image loading
  • Timed tasks, such as setTimeout
    Insert picture description here
    Insert picture description here
    Insert picture description here

Insert picture description here
Insert picture description here

Question answer

What is the difference between synchronous and asynchronous?

Based on JS, it is a single-threaded language.
Asynchrony will not block code execution.
Synchronization will block code execution.

Synchronous is a blocking mode, and asynchronous is a non-blocking mode.
Synchronization means that when a process is executing a request, if the request takes a while to return information, then the process will wait until it receives the return information before continuing;
asynchronous means that the process does not need to wait forever. Go on, but continue to perform the following operations, regardless of the status of other processes. When there is a message return, the system will notify the process for processing, which can improve the efficiency of execution.

Load a picture with Promise by hand

Reasons for Promises
Common callback hell scenarios:


// 回调地狱  callback hell
// 获取第一份数据
$.get(url1, (data1) => {
    
    
    console.log(data1)
    //获取第二份数据
    $.get(url2, (data2) => {
    
    
        console.log(data2)
        //获取第三份数据
        $.get(url3, (data3) => {
    
    
            console.log(data3)
            //...
        })
    })
}

As shown above, multi-asynchronous prone to the following problems:

The execution order of multiple asynchronous returns is uncontrollable.
Multi-asynchronous exception error handling is very complicated.
Multiple asynchronous nesting will lead to callback hell.

We urgently need a guarantee paradigm that can guarantee the order of asynchronous execution, guarantee execution and throw errors in asynchronous processing to solve these problems. The answer ES6 gives us is Promise.
Use promises to deal with the same multiple asynchronous problems:


function getData(url) {
    
    
            return new Promise((resolve, reject) => {
    
    
        $.ajax({
    
    
            url,
            success(data) {
    
    
                resolve(data)
            },
            error(err) {
    
    
                reject(data)
            }
        })
    })
}
var url1 = '/datà1.json'
var url2 = '/datà2.json'
var url3 = '/datà3.json'
getData(url1).then(data1 => {
    
    
    console.log(data1)
    return getData(url2)
}).then(data2 => {
    
    
    console.log(data1)
    return getData(url3)
}).then(data3 => {
    
    
    console.log(data3)
}).catch(err => {
    
    
    console.log(err)
})

Promise turns the callback form into a non-nested form, into a series form

Use Promise to load an image


function loadImg(src2) {
    
    
    return new Promise(
        //参数 resolve reject 均是函数
        (resolve,reject)=>{
    
    
            const img1 = document.createElement('image')
            img1.src = src2
            img1.onload=()=>{
    
    
                resolve(img1)
            }
            img1.onerror=()=>{
    
    
                const err = new Error(`图片加载失败!${
      
      src}`)
                reject(err)
            }
            
        }
    )
}
const url1 = 'https://img4.sycdn.imooc.com/szimg/5dbffa9109ef425a12000676-360-202.png'
const url2 = 'https://img4.sycdn.imooc.com/szimg/5dbffa9109ef425a12000676-360-202.png'
loadImg(url1).then(img=>{
    
    
    console.log(img.width)
    return img
}).then(img=>{
    
    
    console.log(img.height)
    return loadImg(url2)
}).then(img2=>{
    
    
    console.log(img2.width)
    return img2
}).then(img2=>{
    
    
    console.log(img2.height)
})
.catch(err=>{
    
    
    console.log(err)
})

Asynchronous application scenario
  • Network request, ajax image loading
  • Timed tasks, such as setTimeout

Insert picture description here

summary

  • The difference between single thread and asynchronous, asynchronous and synchronous
  • Front-end asynchronous application scenarios: network requests & timing tasks
  • Promise resolution callback hell

JS basics

Review content
content
  • Variable type and calculation
  • Prototype and prototype chain
  • Scope and closure
  • Asynchronous and single threaded
Review topic
Variable types and calculations-topics
  • typeof can determine which types
  • When to use === When to use ====
  • The difference between value type and reference type
  • Handwritten deep copy
Review knowledge points
Variable types and calculations-knowledge points
  • Value type VS reference type, stack model, deep copy
  • typeof operator
  • Type conversion, truly and falseiy variables
Prototype and Prototype Chain-Topic
  • How to accurately determine whether a variable is an array
  • Handwriting a simple jQuery, consider plug-ins and extensibility
  • How to understand the prototype nature of class
Prototype and Prototype Chain-Knowledge Points
  • Class and inheritance, combined with handwritten jQuery examples to understand
  • instanceof
  • Prototype and Prototype Chain: Diagram & Execution Rules
Scope and closure-topic
  • Different application scenarios of this, how to take the value
  • Handwritten bind function
  • Application scenarios of closures in actual development, with examples
    Insert picture description here
Scope and closure-knowledge points
  • Scope and free variables
  • Closures: two common ways & free variable search rules
  • this
Asynchronous and single-threaded-topic
  • What is the difference between synchronous and asynchronous
  • Load a picture with Promise by hand
    Insert picture description here
Asynchronous and single thread-knowledge points
  • The difference between single thread and asynchronous, asynchronous and synchronous
  • Front-end asynchronous application scenarios: network requests & timing tasks
  • Promise resolution callback hell

Guess you like

Origin blog.csdn.net/WLIULIANBO/article/details/114989059