Go through the basic JavaScript skills before interview --- Asynchronous and single thread

Question

a. What's the differences between async and sync?

b. Implement loading an image with Promise.

c. When should you use async on front-end development?

d. What's the input for below code?

console.log(1)
setTimeout(function () {
    console.log(2)
}, 1000)
console.log(3)
setTimeout(function () {
    console.log(4)
},0)
console.log(5)

Skills

1. Asynchronous and single thread

JS is a single thread language, which means only can handle one thing at one time;

JS and DOM rendering use one same thread, as JS have possibility to modify DOM structure.

However, we usually require the application can't be blocked when waiting ( e.g. network request, or scheduled tasks). In this case, we need asynchronous solution.

// async will use callback function and won't block following code execution 
console.log(100)
setTimeout(function () {
    console.log(200)
}, 1000)
console.log(300)

// 100, 300, 200
// sync
console.log(100)
alert(200)
console.log(300)

// 100, alert will block the next code and 300 won't output until you click alert confirm

2. Usage scenarios

// ajax request
console.log('start')
axios.get('./data1.json', (data1)=>{
    console.log(data1)
})
console.log('end')
// image loading
console.log('start')
let img = document.createElement('img')
img.onload = () => console.log('loaded')
img.src = '/xxx.png'
console.log('end')
// setTimeout/setInterval
console.log(100)
setTimeout(function () {
    console.log(200)
}, 1000)
console.log(300)

3. Promise

Promise is to solve callback hell issue.

// callback hell
// get the first data
$.get(url1, (data1)=>{
    console.log(data1)
    
    // get the second data
    $.get(url2, (data2)=>{
    	console.log(data2)
        
        // get the second data
        $.get(url2, (data2)=>{
            console.log(data2)
			
            // more requests...
         })   
     })   
})
// use Promise to solve callback hell
const getData(url) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url,
            success(data) {
                resolve(data)
            },
            error(err) {
                reject(err)
            }
        })
    })
}

// use it like this
getData(url1).then(data1 => {
    console.log(data1)
    return getData(url2)
}).then(data2 => {
    console.log(data2)
    return getData(url3)
}).then(data3 => {
    console.log(data3)
}).catch(err => console.log(err))

4. Implement loading an image with Promise

const loadImg = (src) => new Promise(
	(resolve, reject) => {
        const img = document.createElement('img')
        img.onlond = () => resolve(img)
        img.onerror = () => reject(new Error('failed'))
    	img.src = src
    }
)