I have met a weird behavior of async/await browser fetch API with large file such as:
- When using async/ await with fetch api to call rest api → the code is executed sequentially
await fetch("https://jsonplaceholder.typicode.com/todos/1");
console.log("res 1");
await fetch("https://jsonplaceholder.typicode.com/todos/1");
console.log("res 2");
await fetch("https://jsonplaceholder.typicode.com/todos/1");
console.log("res 3");
apis are fetched sequentially (view in Network tab) → it means that the second api just run after the first one is finished, etc …
I also test this behavior by slowing down network → console.log is also executed with the latter wait the former finish.
But
- When using async/ await with fetch api to download large files → the code is also executed sequentially but the browser fetch (download) files in parallel.
await fetch(
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4");
console.log("fetch 1");
await fetch(
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4");
console.log("fetch 2");
await fetch("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4");
console.log("fetch 3");
The weird thing is browser fetch api does not wait until the fetch done:
-
The console.log are print almost immediately (it works as if the await keyword is ignored).
-
Tab network in debug tool show that these files are fetched (downloaded) in parrallel.
P/s: I also test with axios
and this library work OK (in both cases the api is just executed after the previous one done)