Javascript fetch 异常导致dead stop

Javascript fetch exception causes dead stop

我有以下代码:

        function makeid(length) {
            var result = '';
            var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var charactersLength = characters.length;
            for ( var i = 0; i < length; i++ ) {
                result += characters.charAt(Math.floor(Math.random() * 
            charactersLength));
            };
            return result;
        };

        var instance = "{{ user }}" + makeid(16);
        var checksum = "First Request Not recieved";
        console.log(instance);
        function downloadPlay(){
            console.log("\ndownloadPlay - Begin\n")
            try{
                fetch("/file?instance=" + instance + "&checksum=" + checksum)
                .then(function(resp) {
                    resp.headers.forEach(
                        function(val, key) {
                            // console.log("key, val: " + key + ", " + val); 
                            if(key == "checksum"){
                                console.log("checksum: " + val); 
                                checksum = val;
                            };
                        }
                    );
                }
            )
            .then(file => {
                var audio = new Audio("/file?instance=" + instance + "&checksum=" + checksum);
                console.log("Done");
                audio.addEventListener('ended', (event) => {
                    delete audio;
                    downloadPlay();
                });
                audio.play();
                }
            )
            } catch (error) {
                console.log("Something went wrong, Retrying: " + error);
            }
            console.log("downloadPlay - Complete\n")
        };
        downloadPlay();

当 promise 成功时,这非常有效。然而,当它失败时(例如当客户端设备切换网络时,即 wifi 到数据或同一 wifi 网络上的不同接入点)它会停止并且永远不会恢复,无论有多少 while 循环、额外的递归点或 try and catch 语句我用。到目前为止,我能做的最好的事情就是让它播放越来越多的音频,大部分音频彼此同步,我只是不明白为什么。似乎我对这个 promise 的实际运作方式普遍缺乏理解,但无论我 read/watch 有多少教程,我的理解似乎都没有改变。

如果有帮助的话,下面是一些有用的代码:

        function makeid(length) {
            var result = '';
            var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var charactersLength = characters.length;
            for ( var i = 0; i < length; i++ ) {
                result += characters.charAt(Math.floor(Math.random() * 
            charactersLength));
            };
            return result;
        };

        var instance = "{{ user }}" + makeid(16);
        var checksum = "First Request Not recieved";
        console.log(instance);
        function downloadPlay(){
            console.log("\ndownloadPlay - Begin\n")
            try{
                console.log('fetching')
                fetch("/file?instance=" + instance + "&checksum=" + checksum)
                .then(function(resp) {
                    resp.headers.forEach(
                        function(val, key) {
                            // console.log("key, val: " + key + ", " + val); 
                            if(key == "checksum"){
                                console.log("checksum: " + val); 
                                checksum = val;
                            };
                        }
                    );
                }
            ).catch(function(error) {
                console.log('request failed', error)
                console.log('retrying')
                downloadPlay();
                return;
            })
            .then(file => {
                var audio = new Audio("/file?instance=" + instance + "&checksum=" + checksum);
                console.log("Done");
                audio.addEventListener('ended', (event) => {
                    delete audio;
                    downloadPlay();
                });
                audio.play();
                }
            )
            } catch (error) {
                console.log("Something went wrong, Retrying: " + error);
            }
            console.log("downloadPlay - Complete\n")
        };
        downloadPlay();

对于我做错了什么的任何解决方案或非常简单的解释将不胜感激 提前致谢:)

你可以这样做

只需删除评论并使用您原来的抓取功能

除非使用 async await,否则不能使用 try catch 和 promises

const fakeChecking = Promise.resolve({headers: {checksum: 'aaaa'}})
const errorChecking = Promise.reject('error')

function downloadPlay(fetching) {
  console.log("\ndownloadPlay - Begin\n")

  console.log('fetching')
  fetching
    .then((resp) =>  resp.headers.checksum)
    .then(checksum  => {
      /*var audio = new Audio("/file?instance=" + instance + "&checksum=" + checksum);
      console.log("Done");
      /*audio.addEventListener('ended', (event) => {
        delete audio;
        downloadPlay();
        console.log("downloadPlay - Complete\n")
      });
      audio.play();*/
      console.log("downloadPlay - Complete\n")
    })
    .catch(function(error) {
      console.log('request failed', error)
      console.log('retrying')
      downloadPlay(fakeChecking);
    })
   
};

downloadPlay(errorChecking);