0

I've a Upload file functionality, I send the file in parts so, many request was made, when I upload the file I use async : 'true' in $.ajax({});, then when I click in other tab, request to get list of book's names for example ... and request is waiting and is made when all request of Upload was finished.

I need a promise in my code ? or $.when() is better ?

My code is:

$("#Upload").click(function (){
   ...
   sendFile(file, blockLength, numberOfBlocks).then(()=>{
      //All request are made
   });
});


async function sendFile(file, chunkSize, numberOfBlocks) {
     ...
     function sendNextChunk () {
             $.ajax({
                    async: true,
                    type: 'POST', url: "URL",
                    headers: headers,
                    data: fileChunk,
                    cache: false,
                    contentType: false,
                    processData: false
             }
             ...
             if (currentChunk <= numberOfBlocks) {
                await sendNextChunk();
              }
     }

    await sendNextChunk();

}

In the network is like:

/UPload?chunk=1      200
/UPload?chunk=2      200
/UPload?chunk=3      200
/getBooksList        pending        < - Here is pending until all request of Upload are made
/UPload?chunk=4      200
/UPload?chunk=5      200
/UPload?chunk=6      pending
/UPload?chunk=7      pending
/UPload?chunk=8      pending
/UPload?chunk=9      pending
/UPload?chunk=10     pending
...
  • 1
    you're not using `sync`, you're using (correctly) `async` ... and you don't need a promise, since jquery $.ajax already returns a promise-like object – Jaromanda X Mar 23 '20 at 05:23
  • but, since you are not returning the promise-like object in `function sendNextChunk` - there's no point `await`ing it ... and since `sendNextChunk` isn't tagged `async` you can't `await sendNextChunk()` inside `sendNextChunk` as your code implies – Jaromanda X Mar 23 '20 at 05:25
  • Well, then I will only return $.ajax and SendFile().then(); is correct? But the sendNextChunk() send request one by one until all requests are made? – Jorge Mar 23 '20 at 05:32
  • `return $.ajax` won't actually solve the issue, since your conditional will never run if you do - you need to re-think your strategy. `sendFile` doesn't even need to be async, since the one and only `await` is the last statement - you can simply `return sendNextChunk()` without the `async` tag, and the result is the same – Jaromanda X Mar 23 '20 at 05:36
  • I think perhaps https://pastebin.com/K0u4wLkB will do as you want (assuming you add whatever `...` means in your code :p ) – Jaromanda X Mar 23 '20 at 05:38
  • Well! work fine! , thank you so much for your help – Jorge Mar 23 '20 at 05:57

0 Answers0