JavaScript异步回调在我的情况下似乎不起作用

时间:2019-12-22 19:39:24

标签: javascript

我对JavaScript及其异步机制不太熟悉。

在代码中,我尝试加载.txt文件并进行检查。文件加载后,我想计算一些东西。在运行函数fct_lv1之后,我要打印存储在ttl中的计数结果。但是,即使使用了回调,打印结果也将始终为0

我也使用了setTimeout机制来实现,它成功了。但是这种方法不是我的首选。

您对如何通过回调机制或其他方式打印最终ttl值有任何建议吗?

<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<html>
<title>Txt Counting</title>
<head>
</head>
<script>

async function run(){    
    heheda = fetch("http://localhost:8080/label_link.txt")
    // //after loading an txt, I want to count something, and the counting result will be in the variable ttl. 
    .then(response => response.text())
    .then((data) =>{
        // this variable is for us to update. 
        let ttl = 0;
        var count = function(){
            ttl += 1;
        };
        var_print = function(){
            console.log("in callback: ", ttl);
        }
        fct_lv1 = function(callback_lv1){
            //iterate for 10 times, after each time, the ttl will add 1. 
            for(let i = 0; i < 10; i++){
                fct_lv2 = function(callback_lv2){
                    let online_img = document.createElement("IMG"); 
                    online_img.setAttribute("src", "https://images-na.ssl-images-amazon.com/images/I/719fF478nPL._SX425_.jpg");
                    online_img.setAttribute("width", "224");
                    online_img.setAttribute("height", "224");
                    online_img.onload = function(){
                        callback_lv2();
                    }   
                }
                fct_lv2(count);
            }
            // It seems that the callback is not working here. 
            callback_lv1();
        }
        fct_lv1(var_print);

        // this method can print the updated ttl. 
        setTimeout(function(){
            console.log("in time out:", ttl);
        }, 1000);
    });
}
run(); 
</script>
<body>
    <p  id="accuracy"></p>
</body>
</html>

0 个答案:

没有答案