Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

sequential - Loading files synchronously in Javascript with await operator

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...