js中promise解决callback回调地狱以及使用async+await异步处理的方法

1、callback回调地狱

 

function ajax(fn) {
    setTimeout(()=> {
        console.log('你好')
        fn()
    }, 1000)
}
ajax(() => {
    console.log('执行结束')
    ajax(()=>{
        console.log('执行结束')
        ajax(()=>{
            console.log('执行结束')
            ajax(()=>{
                console.log('执行结束')
            })
        })
    })
})

2、promise解决回调地狱

function delay(word) {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve(word)
        }, 2000)
    })
}

delay('孙悟空')
    .then((word)=>{
        console.log(word)
        return delay('猪八戒')
    })
    .then((word)=>{
        console.log(word)
        return delay('沙悟净')
    })
    .then((word) => {
        console.log(word)
    })
    .catch
console.log('执行结束')

3、async+await优雅处理异步

function delay(word) {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve(word)
        }, 2000)
    })
}

async function start() {
    const word1 = await delay('孙悟空')
    console.log(word1)
    const word2 = await delay('猪八戒')
    console.log(word2)
    const word3 = await delay('沙悟净')
    console.log(word3)
}
start()

 

猜你喜欢

转载自www.cnblogs.com/nayek/p/11701316.html