0

We are trying to download binary files by using the await fetch as illustrated in the following function. The steps that the following function should be doing are the following:

  1. we receive a URL as argument
  2. we retrieve the Blob
  3. Call-Function to C++

The expected result is illustrated in section 1. The wrong result that we are getting is illustrated in section 2. It's as if the Call-Back function is being ignored, the fetches are being done as if the call-back function doesn't exist.

By looking at the following piece of code. Do you see anything wrong in how await and fetch are being done.

We do not want and cannot use XMLHttpRequest.


async download(sUrl: string): Promise<void> {
    
    const fetRes:Response = await fetch(sUrl, {method: eHttpMethod.GET})
    const BlobRes:Blob = await fetRes.blob()
  

    //Call Back function (This is a C++ function that I can't show)
    //this.CALLBACK(WEBSOCKET,  readyStage,'iDOINVOKE');

}

download("url1");
download("url2");
download("url3");

1. Expected Output:

"url1"
CallBack
"url2"
CallBack
"url3"
CallBack

2. Wrong Ouput:

"url1"
"url2"
"url3"
CallBack
CallBack
CallBack
Hani Gotc
  • 840
  • 11
  • 24
  • 1
    https://stackoverflow.com/questions/27265818/does-the-use-of-async-await-create-a-new-thread this is intended behavior. Your code is working in that it essentially "queues" up all of the "long calls" to get `url1-3` then once those return, continues evaluating past the awaits. – Ryan Schaefer Jul 16 '21 at 13:45

1 Answers1

2

If you want to make the downloads run sequentially, you should await them:

await download("url1");
await download("url2");
await download("url3");

You can only use await within a function, though, so you probably want something like this:

async downloads() {
  await download("url1");
  await download("url2");
  await download("url3");
}

downloads();
edemaine
  • 2,699
  • 11
  • 20
  • edemaine do you want something funny? we did the same thing earlier and yet we are still getting the same behaviour. It's NUTS! we thought that it was the solution – Hani Gotc Jul 16 '21 at 14:13
  • 1
    We'd need to see an actual example of the code to help further. – edemaine Jul 16 '21 at 14:15