js FE

js 异步方案

callback、promise、generator、async

Posted by nolan on January 5, 2020

callback 是最初的方案

function _fetch(callback){
    const xhr = new XMLHttpRequest()
    xhr.onReadyStateChange = ()=> {
        if(xhr.readyState = xhr.Done && xhr.status == 200 ){
            callback(xhr.responseText)
        }
    }
    xhr.open('GET','http://localhost:8899')
    xhr.send()
}

let data;
_fetch((res)=>{
    data = res.data;
})

promise 使代码扁平化,减少回调地狱

function _fetch(){
    return new Promise((resolve,reject) => {
        const xhr = new XMLHttpRequest()
        xhr.onReadyStateChange = ()=> {
            if(xhr.readyState = xhr.Done && xhr.status == 200 ){
                resolve(xhr.responseText)
            }
        }
        xhr.open('GET','http://localhost:8899')
        xhr.send()
    })
}

let data;
_fetch()
.then((res)=>{
    data = res.data
})

generator yield * 配合 co 使代码同步化

function _fetch(){
    return new Promise((resolve,reject) => {
        const xhr = new XMLHttpRequest()
        xhr.onReadyStateChange = ()=> {
            if(xhr.readyState = xhr.Done && xhr.status == 200 ){
                resolve(xhr.responseText)
            }
        }
        xhr.open('GET','http://localhost:8899')
        xhr.send()
    })
}

co(function *(){
    let data = yield _fetch()
    console.log(data)
})

async await 使同步化的代码进一步简洁化

function _fetch(){
    return new Promise((resolve,reject) => {
        const xhr = new XMLHttpRequest()
        xhr.onReadyStateChange = ()=> {
            if(xhr.readyState = xhr.Done && xhr.status == 200 ){
                resolve(xhr.responseText)
            }
        }
        xhr.open('GET','http://localhost:8899')
        xhr.send()
    })
}

(async () => {
    let data = await _fetch()
    console.log(data)
})()