-1

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Fernando
  • 1,477
  • 2
  • 14
  • 33
  • `await` doesn't make your code synchronous. It allows you to write code that *looks* synchronous (and thus is maybe easier to follow). If you want to fetch files sequentially you just `await` the fetches in sequence: `var a = await fetchFile(...); var b = await fetchFile(...); ...`. – Felix Kling Feb 27 '17 at 03:28
  • All you need is the [Fetch API](https://developer.mozilla.org/en/docs/Web/API/Fetch_API). – Ry- Feb 27 '17 at 03:29

1 Answers1

0

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.

Fernando
  • 1,477
  • 2
  • 14
  • 33