Callback, Promise和Async/Await的对比

Callback, PromiseAsync/Await的对比

Callback Hell

getData1(function (data1) {
    console.log('我得到data1了')
    
    getData2(function (data2) {
        console.log('我得到data2了')
        console.log('data1 + data2 = ...')
    })
})

Promise

function getData1() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(1111)
        }, 5000)
    })
}

function getData2() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(2222)
        }, 10000)
    })
}

function doSomething() {
    let p1 = getData1().then(function (data) {
        console.log('请求成功: data1 = ' + data)
        return data
    })
    let p2 = getData2().then(function (data) {
        console.log('请求成功: data2 = ' + data)
        return data
    })
    Promise.all([p1, p2]).then(function (data) {
        var sum = data[0] + data[1]
        console.log('data1 + data2 = ' + sum)
    })
}

Async/Await

async function getData1() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(1111)
        }, 5000)
    })
}
async function getData2() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(2222)
        }, 5000)
    })
}

async function doSomething() {
    var data1 = await getData1()
    console.log('请求成功: data1 = ' + data1)

    var data2 = await getData2()
    console.log('请求成功: data2 = ' + data2)

    var sum = data1 + data2
    console.log('data1 + data2 = ' + sum)
    
}

posted @ 2018-01-19 17:02  赵康  阅读(941)  评论(0编辑  收藏  举报