promise手写?(回调地狱)

学前端的应该都听过回调地狱吧,那么回调地狱是什么?怎么解决?

一般回调地狱有这两种:

第一种:

getData({
    url:'http://localhost:3000/get',
    success:(data)=>{
        getData({
            url:'http://localhost:3000/getBooks?id=1',
            success:data=>{
                console.log(data)
                getData({
                    url:'http://localhost:3000/getNews?id='+data[0].id,
                    success:data=>{
                        console.log(data)
                }
            })
        }
    })
}})

第二种:

getDataPromise('http://localhost:3000/get').then(data => {
    return getDataPromise('http://localhost:3000/getBooks?id='+data[0].id)
}).then(data => {
    return getDataPromise('http://localhost:3000/getNews?id='+data[0].id)
}).then(data => {
    console.log(data)
})

解决方法:

async function get(){
    const res1 = await getDataPromise('http://localhost:3000/get')
    const res2 = await getDataPromise('http://localhosr:3000/getBooks?id='+res1[0].id)
    const res3 = await getDataPromise('http://localhosr:3000/getNews?id='+res2[0].id)
    console.log(res3)
}
get()

猜你喜欢

转载自blog.csdn.net/swoly2894265391/article/details/125221976