Sending data in chunks using Vue.js

I'm interested in sending the data in chunks. Currently, what I send to the server looks like this: for loop - 1, 2, 3. However, the server receives it asynchronously as 3, 1, 2 and I need it to be received synchronously in the order of my for loop: 1, 2, 3. How can I achieve this?

//52428800
                const chunkSize = 1377628
                let beginUpload = data;
                let component = this;
                let start = 0;
                let startCount = 0;
                let callStoreCouunt = 0;

                for (start; start < zipedFile.length; start += chunkSize) {
                    const chunk = zipedFile.slice(start, start + chunkSize + 1)
                    startCount +=1;
                        // debugger
                        // var base64Image = new Buffer( zipedFile ).toString('base64');
                        var base64Image = new Buffer( chunk ).toString('base64');
                        console.log(chunk, startCount);

                    let uploadPackage: documentInterfaces.UploadPackage = {
                        transaction: {
                            documentId: {value: data.documentId.value},
                            transactionId: data.transactionId,
                            fileGuid: data.fileGuid
                        },
                        packageBuffer: base64Image
                    };
                    // debugger

                    


                    component.$store.dispatch('documents/uploadPackage', uploadPackage)
                    .then(({ data, status }: { data: documentInterfaces.ReciveAttachScene , status: number }) => {
                        // debugger
                        if(status !== 200){
                            component.$message({
                                message: data,
                                type: "error"
                            });
                            component.rejectUpload(beginUpload);
                        }
                        else{
                            callStoreCouunt+=1;
                            console.log(chunk, "res" + callStoreCouunt)
                            debugger
                            if(callStoreCouunt === startCount){

                                let commitPackage = {
                                    transaction: {
                                        documentId: {value: uploadPackage.transaction.documentId.value},
                                        transactionId: uploadPackage.transaction.transactionId,
                                        fileGuid: uploadPackage.transaction.fileGuid
                                    }
                                };
                              debugger
                                component.commitUpload(commitPackage);
                            }
                        }
                        });
                    }

Answer №1

Data transmission can be unpredictable, with chunks of data taking different paths and potentially circling the globe before reaching the server due to network issues.

Even if one chunk is sent a few milliseconds earlier than another, it doesn't guarantee it will reach the server first.

To address this issue, there are several solutions:

Solution 1:

Wait for the server response before sending the next chunk:

let state = {
  isPaused: false
}
let sentChunks = 0
let totalChunks = getTotalChunksAmount()
let chunkToSend = ...

setInterval(() => {
  if (!isPaused && sentChunks < totalChunks) {
    state.isPaused = true
    send(chunkToSend)
    sentChunks += 1
  }
}, 100)

onServerReachListener(response => {
  if (response === ...) {
    state.isPaused = false
  }
})

Solution 2:

If real-time sequential processing isn't necessary, wait for all chunks to arrive at the server and then sort them before processing:

let chunks = []
onChunkReceived (chunk) {
  if (chunk.isLast) {
    chunks.push(chunk)
    chunks.sort()
    processChunks()  
  }
  else {
    chunks.push(chunk)
  }
}

Solution 3:

If real-time sequential processing is required, assign an id property to each chunk for sequential processing while storing any out-of-order chunks for later:

let chunksToProcess = []
let lastProcessedChunkId = -1 
 
onChunkReceived (chunk) {
  if (chunk.id === lastProcessedChunkId) { 
    processChunk()
    lastProcessedChunkId += 1
    processStoredChunks()
  }
  else {
    chunksToProcess.push(chunk)
  }
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving data from a React state in one component and utilizing it in a separate component

Thank you for taking the time to assist me with this challenge. I am currently working on a project that involves creating the state goodData in one component called AddProduct and accessing it in another component named ActionBox, both within the same j ...

What is the functionality of the save callback in Mongoose?

Currently in the process of learning about Mongoose's save() function for the MEAN stack. This particular function requires a callback as outlined in its API documentation: Model#save([options], [fn]) Saves this document. Parameters: [options] < ...

Seems like JavaScript's .active functionality is failing to function properly in my case

I'm encountering an issue with my website's homepage. I have a list of services displayed, and the intention is for a description to appear when one of the services is clicked. However, clicking on the buttons does not trigger the expected action ...

Error: Attempting to access property 'setData' of an undefined object results in a TypeError [Slider]

I encountered an error with my slider that says Uncaught TypeError: Cannot read property 'setData' of undefined. The error occurs when I use material ui as a component along with redux-form. This issue happens specifically when the slider is bein ...

Is it possible to use an angular expression as the ng-click function?

I have been searching everywhere for the answer to this question. Within my code, there is an angular object called column.addOnParams. This object includes a child element named rowClick, which can be accessed using column.addOnParams.rowClick. The val ...

Error message: Attempting to access the property '_layerAdd' of an undefined object in the context of vue and leaflet integration

Encountering an issue while attempting to include a feature group on my map: TypeError: Cannot read property '_layerAdd' of undefined The section of code causing the error: <l-map id="mapid" :zoom="zoom" :center="center" /> var ...

JS filter function is not functioning as expected. It's unclear what the issue might be

Check out my previous inquiry What could be the issue with my filter? I've implemented a filter, but it seems to have some glitches when dealing with specific values. The 'No Record Found' message doesn't appear as expected in certain ...

Unexpected loading glitches occurring in vue-material components

I recently delved into the world of Vue.js and VueMaterial, which has been a refreshing and new experience for me since I've mostly focused on Native Android development in the past. Currently, I'm facing an unusual issue that seems to stem from ...

Hiding the C3 tooltip after engaging with it

I'm currently expanding my knowledge on utilizing C3.js for creating charts, and one aspect I'm focusing on is enhancing the tooltip functionality. Typically, C3 tooltips only appear when you hover over data points as demonstrated in this example ...

Troubleshooting: AngularJS Form Submission Failure

As a novice in Angular and not a JavaScript expert, I am facing challenges with form submission. My task involves loading movie showtimes from an http API and using ng-repeat to display them within a page container. The REST API requires a zipcode input, w ...

Compare the precise value of $(window).height() to a specific scroll value

Initially, I retrieve $(window).height() and compare this height with the specific scroll value. $(window).scroll(function (event) { var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); console.log("window hei ...

Does catching errors cause the for loop to stop in JavaScript?

for (let index = 0, total = IDs.length; index < total; index++) { item = IDs[index]; hasError = false; try{ let id = db.getSiblingDB("door").jhi_user.findOne({"_id" : item}); } catch (error){ failedIDs.push(item); ...

Error: The method specified in $validator.methods[method] does not exist

Having trouble solving a problem, despite looking at examples and reading posts about the method. The error I'm encountering is: TypeError: $.validator.methods[method] is undefined Below that, it shows: result = $.validator.methods[method].call( t ...

Choose a navigation item from the list containing a nested span element

I've implemented selectnav from GitHub and it's functioning perfectly. However, my menu consists of list items with a description span inside each one, resulting in menu items structured as shown below: <li><a href="somelink.html">Ch ...

What is the most efficient way to execute a method multiple times concurrently in C# using tasks?

My goal is to execute a method that performs time-consuming tasks from multiple threads. Public void DoSomeWork(int n) { // This method involves time-consuming operations based on n } 1 - Instead of utilizing threads and threadpool, I am exploring the ...

React is having trouble loading the page and is displaying the message "Please enable JavaScript to use this application."

Following a tutorial at https://learn.microsoft.com/en-us/learn/modules/build-web-api-minimal-spa/5-exercise-create-api Everything was going smoothly until I reached this step: Add the following proxy entry to package.json: "proxy": "http:/ ...

Incorporating an NPM module with dependencies within the Meteor framework

I'm encountering some difficulties while attempting to integrate an NPM package into my meteor project. The specific module I am trying to utilize is the steam package. In order to make this work, I have included the meteorhacks:npm package for mete ...

nodejs callbacks and their return values

Hey guys, I'm having trouble resolving an issue with a JavaScript callback return. Here's the function in question: //Function to get user's contact list function get_contact_list(data) { //Retrieve user ID based on ...

Why is my Angular form submitting twice?

Currently, I am working on a user registration form using AngularJS with ng-submit and ng-model. However, I am facing an issue where the form triggers submission twice when the user submits it. I have checked for common causes such as declaring the contro ...

trigger an event once an element has completed cycling using cycle.js

Incorporating the cycle.js library for simple transitions between images: $(document).ready(function() { var first; var $slider = $(".trauringe"); $slider.cycle({ timeout: 8000, next: '#next', prev: '#prev' ...