Skip to content

异步 - 解答

仲灏约 1 分钟

异步 - 解答

同步和异步的区别是什么?分别举一个同步和异步的例子

  • 基于单线程
  • 异步不会阻塞代码运行
  • 同步会阻塞代码运行

一个关于setTimeout的笔试题

javascript
// setTimeout 笔试题
console.log(1)
setTimeout(function () {
    console.log(2)
}, 1000)
console.log(3)
setTimeout(function () {
    console.log(4)
}, 0)
console.log(5)
// 结果顺序 1 3 5 4 2

手写用 Promise 依次加载两张图片

js
function loadImg(src) {
    const promise = new Promise((resolve, reject) => {
        const img = document.createElement('img')
        img.onload = () => {
            resolve(img)
        }
        img.onerror = () => {
            reject(new Error(`图片加载失败 ${src}`))
        }
        img.src = src
    })
    return promise
}

const src = 'http://www.imooc.com/static/img/index/logo_new.png'

loadImg(src).then(img => {
    console.log(img.width)
    return img
}).then(img => {
    console.log(img.height)
}).catch(ex => {
    console.error(ex)
})

前端使用异步的场景有哪些

  • 网络请求,如 ajax 图片加载
  • 定时任务,如 setTimeout

上次更新:

讨论区

欢迎留下想法与补充