Skip to content
Advertisement

Typescript: Call-Back Function called much later in the code after await fetch

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

Answer

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();
Advertisement