promise解决回调地狱问题

什么是回调地狱? 如何解决呢、。

可以看B站的视频https://search.bilibili.com/all?keyword=%E5%9B%9E%E8%B0%83%E5%9C%B0%E7%8B%B1&from_source=webtop_search&spm_id_from=333.794

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="./libs/jquery-3.4.1.min.js"></script>
</head>

<body>
    <script type="text/javascript">
        window.onload = function () {
            console.log(123);
            const ID_BASE_URL = 'https://jsonplaceholder.typicode.com/todos';
            const ROBOT_IMG_BASE_URL = 'https://robohash.org/';


            // 获取机器人id
            function getRobotId(url, callbacks) {
                $.get(url, function (data) {
                    const id = data.id;
                    callbacks(id);
                })
            }

            //创建机器人
            function createRobot(id) {
                const img = document.createElement('img');
                img.src = ROBOT_IMG_BASE_URL + `/${id}?size=200x200`;
                document.body.appendChild(img);
            }

            //回调地狱,一层一层嵌套,看得很难受
            // getRobotId(ID_BASE_URL + '/1', function (id) {
            //     createRobot(id);
            //     getRobotId(ID_BASE_URL + '/2',function(id){
            //         createRobot(id);
            //         getRobotId(ID_BASE_URL + '/3',function(id){
            //         createRobot(id)
            //     })
            //     })
            // });
            

                function getRobotIdPromise(url){
                    const promise = new Promise(
                        (resolve,reject)=>{
                            $.get(url,function(data){
                                const id = data.id;
                                resolve(id);
                        })
                        }
                        )
                        return promise;
}

//promise 平铺开来,只有一层哦
getRobotIdPromise(ID_BASE_URL+'/1').then(function(id){
    createRobot(id);
    return getRobotIdPromise(ID_BASE_URL+'/2')
}).then(
    function(id){
    createRobot(id);
    return getRobotIdPromise(ID_BASE_URL+'/3')}
)
        }
    </script>

</body>

</html>
原文地址:https://www.cnblogs.com/zhuangdd/p/14698539.html