Loading files synchronously in Javascript with await operator

风流意气都作罢 提交于 2019-12-25 17:44:31

问题


Recently, I've read that there is a await operator in Javascript for waiting for a Promise object returned by an async function.

My goal is to use just functions that are provided by the standard Javascript without the need of any external libraries. So my question is: how can I efficiently use the await operator for fetching data from server sequentially (one file after the other)?


回答1:


I've managed to get what I was looking for. The first step is to create a async function and then, put all your code, that you need to be executed as if it were synchronous, within that function. Here is a code snippet for that:

<html>
<body>
</body>
</html>

<script>

var fileList = [ 
'test_1.txt', 
'test_2.txt',
'test_3.txt',
'test_4.txt',
'test_5.txt'
];

async function loadFiles() 
{
    for (i = 0; i < fileList.length; i++)
    {
        await fetch(fileList[i]).then(function(response){
            return response.text();
        }).then(function (text){
            console.log(text);
        });
        console.log("loaded " + fileList[i]);
    }
}

loadFiles();

</script>

With this, all the files will be loaded one, after the another. It is pretty amazing to do this in these days, since it is easy to manage sequential tasks in javascript that were done asynchronously before.



来源:https://stackoverflow.com/questions/42477069/loading-files-synchronously-in-javascript-with-await-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!