Callback, Promise和Async/Await的对比

2023-10-17 09:56:12 浏览数 (2)

Callback, PromiseAsync/Await的对比

Callback Hell

代码语言:javascript复制
getData1(function (data1) {
    console.log('我得到data1了')
    
    getData2(function (data2) {
        console.log('我得到data2了')
        console.log('data1   data2 = ...')
    })
})

Promise

代码语言:javascript复制
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

代码语言:javascript复制
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)
    
}

0 人点赞