fetch同步

2023-09-04  本文已影响0人  xueyueshuai
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let http = (url) => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log(new Date() + 'who come :' + url)
          if (url == 3) {
            resolve(url)
          } else {
            reject('不是我想要的')
          }
        }, 1000)
      }).catch(err => {

      })

      // return new Promise((resolve, reject) => {
      //   fetch(url)
      //     .then((response) => {
      //       return response.json();
      //     })
      //     .then((res) => {
      //       resolve(res);
      //     })
      //     .catch((err) => {
      //       console.log(err)
      //     })
      // });
    }


    let func = async (urls = [], urlIndex = 0) => {
      if (urls.length === 0) {
        return false;
      }
      let res = await http(urls[urlIndex]);

      let nextIndex = urlIndex + 1;
      if (nextIndex >= urls.length) {
        return false;
      } else {
        return func(urls, nextIndex)
      }


      // if (res) {
      //   return res;
      // } else {
      //   let nextIndex = urlIndex + 1
      //   if (nextIndex >= urls.length) {
      //     return false;
      //   } else {
      //     return func(urls, nextIndex)
      //   }
      // }
    }

    // 此处为调用处
    func([1, 2, 3, 4, 5]).then(res => {
      console.log(res)
    })
  </script>
</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读