having large amount of browser data - json sent to the server side, so wanna to chunk the data and send to the server sequentially with sleep 1 seconds between each sending.
have tried two ways: way 1:
let url = "http://localhost:3000/api/v1/test";
let chunkSize = 100;
const chunks = data.reduce((acc, _, i) => {
if (i % chunkSize === 0) acc.push([]);
acc[acc.length - 1].push(array[i]);
return acc;
}, [] as T[][]);
console.log('chunks',chunks);
for (const chunk of chunks) {
console.log( 'chunk',chunk.length);
await fetch( url , {
method: 'POST',
body: JSON.stringify( chunk ) ,
"Content-type": "application/json; charset=UTF-8"
}
});
await setTimeout(function(){},1000);
console.log( 'chunk',chunk.length);
however when testing, the process gets stuck when sending the first chunk, no error showing up, just stuck.
second way:
let url = "http://localhost:3000/api/v1/test";
let chunkSize = 100;
const chunks = data.reduce((acc, _, i) => {
if (i % chunkSize === 0) acc.push([]);
acc[acc.length - 1].push(array[i]);
return acc;
}, [] as T[][]);
return Promise.all(chunks.map(async chunk => {
console.log( 'chunk',chunk.length);
await setTimeout(function(){},1000); // not working at all
return await fetch( url , {
method: 'POST',
body: JSON.stringify( chunk ) ,
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
}));
the problem with this above is await setTimeout(function(){},1000); never sleeps.
await new Promise(resolve => setTimeout(resolve, 1000));in the FIRST code, the second code is a complete waste of effort