美文网首页
fetch同步

fetch同步

作者: xueyueshuai | 来源:发表于2023-09-04 10:00 被阅读0次
    <!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>
    

    相关文章

      网友评论

          本文标题:fetch同步

          本文链接:https://www.haomeiwen.com/subject/geovpdtx.html