promise优化回调地狱

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script>
      const ID_BASE_URL = 'https://jsonplaceholder.typicode.com/todos'
      const ROBOT_IMG_BASE_URL = 'https://robohash.org'
      function getRobotId(num, callback) {
        $.get(`${ID_BASE_URL}/${num}`, (data) => {
          const id = data.id
          callback(id)
        })
      }

      function createBobot(id) {
        const img = document.createElement('img')
        img.src = ROBOT_IMG_BASE_URL + `/${id}?size=200x200`
        document.body.appendChild(img)
      }

      function getRobotIdPromise(num) {
        const promise = new Promise((res, rej) => {
          $.get(`${ID_BASE_URL}/${num}`, (data) => {
            const id = data.id
            res(id)
          })
        })
        return promise
      }

      getRobotIdPromise(1)
        .then((id) => {
          createBobot(id)
          return getRobotIdPromise(2)
        })
        .then((id) => {
          createBobot(id)
          return getRobotIdPromise(3)
        })
        .then((id) => {
          createBobot(id)
          return getRobotIdPromise(4)
        })
        .then((id) => {
          createBobot(id)
          return getRobotIdPromise(5)
        })
        .then((id) => {
          createBobot(id)
        })

      // 回调地狱
      // getRobotId(1, (id) => {
      //   createBobot(id)
      //   getRobotId(2, (id) => {
      //     createBobot(id)
      //     getRobotId(3, (id) => {
      //       createBobot(id)
      //       getRobotId(4, (id) => {
      //         createBobot(id)
      //         getRobotId(5, (id) => {
      //           createBobot(id)
      //         })
      //       })
      //     })
      //   })
      // })
    </script>

 

posted @ 2021-08-22 16:58  吴小明-  阅读(53)  评论(0编辑  收藏  举报