使用await运算符在Javascript中同步加载文件 [英] Loading files synchronously in Javascript with await operator

查看:108
本文介绍了使用await运算符在Javascript中同步加载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我读到Javascript中有一个await运算符,用于等待异步函数返回的Promise对象.

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

我的目标是仅使用标准Javascript提供的功能,而无需任何外部库.所以我的问题是:如何有效地使用await运算符顺序地从服务器(一个文件接一个文件)中获取数据?

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

推荐答案

我设法找到了想要的东西. 第一步是创建一个async function,然后将所有需要以同步方式执行的代码放入该函数中. 这是为此的代码段:

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>

这样,所有文件都将一个接一个地加载. 如今,这样做非常令人惊奇,因为可以很容易地用JavaScript来管理以前异步完成的顺序任务.

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.

这篇关于使用await运算符在Javascript中同步加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆