How to change Promise.all to send requests one by one

How to change Promise.all to send requests one by one

I have a an array of chunked data that I need to upload one chunk at time. The current implementation I used it to encapsulate the logic in an Promise.all() since I need to return the result of the promise, The problem with this approach is that all the upload is done asynchronously resulting in a Timeout error as the server can't process all the requests at the same time, How can I modify this method so that the upload is done one chunk at time ?.

My code:

var chunks = _.chunk(variableRecords, 30);
return Promise.all(
        chunks.map(chunk => this.portalService.updateDataForChart(variableId, chunk)))
        .then((updateRes: boolean[]) => {
          if (updateRes.every(updateStatus => updateStatus)) {
            return this.executeRequest<HealthDataSource, boolean>({
              path: `/variable/user/datasources/${dataSource.identifier}`,
              method: 'PUT',
              body: {
                libelle: dataSource.datasource.libelle,
                type: dataSource.datasource.type,
                lastSyncDate: Math.max(maxDate, dataSource.datasource.lastSyncDate)
              },
              headers: this.getHeaders()
            });
          } else {
            return false;
          }
        });


You need them in SEQUENCE , for of is the way to go :

async function chunksSequence(chunks) {
  for(const chunk of chunks) {
    await // your other code here
  }
};

If you need to return something

async function chunksSequence(chunks) {
  let results = []
  for(const chunk of chunks) {
    let result = await // your other code here
    results.push(result)
  }
  return results 
};

Because of comment needed in a promise on return

async function chunksSequence(chunks) {
 return new Promise((resolve, reject)=>{
    let results = []
    for(const chunk of chunks) {
      let result = await // your other code here
      results.push(result)
    }
    resolve(results) 
  }
};

Manage Multiple Requests with Promise.all, Promise.all joins two or more promises and returns only when all the 1:41 So in other words, it's composing multiple promises into a single returned promise. JavaScript promises provide an easier, more efficient way to fire off and keep track of multiple async operations at the same time with Promise.all . >Promise.all</code> joins two or more promises and returns only when all the specified promises have completed or been rejected.


You can do this with the help of Array.reduce()

const chunks = _.chunk(variableRecords, 30);
return tasks.reduce((promiseChain, currentTask) => {
    return promiseChain.then(chainResults =>
        currentTask.then(currentResult =>
            [ ...chainResults, currentResult ]
        )
    );
}, Promise.resolve([])).then(arrayOfResults => {
    // Do something with all results
});

Source : https://decembersoft.com/posts/promises-in-serial-with-array-reduce/

Promise API, If you would just execute a bunch of requests, there is no chance to get all responses into one array just by calling them after each other. Rejecting Promise.all() in Javascript. If you create three promises and two Promise resolved but one rejects then promise.all() method will reject the Promise. If we want many promises to execute in parallel and wait until all of them are ready, then the Promise .all() is useful because if one of them will fail, then it rejects the whole Promise.


If you don't / can't use await you could use something like this

function runSequenceItem(chunks, index) {
 return new Promise(chunks[index])
  .then(res => {
     index ++
     if (index < chunks.length) {
       return runSequence(chunks[index], index + 1)
     } else {
       // this is not needed actually
       return 'done'
     }
   })
}

function runInSequence(chunks) {
 return runSequenceItem(chunks, 0)
}

If you also need the results then you can return an array at the end of the recursion runInSequence

    function runSequenceItem(chunks, index, results) {
 return new Promise(chunks[index])
  .then(res => {
     results.push(res)
     index ++
     if (index < chunks.length) {
       return runSequence(chunks[index], index + 1)
     } else {
       return results
     }
   })
}

function runInSequence(chunks) {
 return runSequenceItem(chunks, 0, [])
}

and then retrieve it at the end

let results = runInSequence(chunks)

Sync up multiple Promises to a single result set with Promise.all, The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. https://github.com/mdn/interactive-examples and send us a pull request. It is possible to change this behaviour by handling possible rejections: In this Angular 8/9/10 Promise tutorial, we are going to learn how to manage asynchronous HTTP response with JavaScript Promise objects. Get the full code of this tutorial on the following GitHub repo: Git Repo Introduction to JavaScript Promise Promises in ECMAScript are very much identical to the promises we make in our daily life. […]


Promise.all(), Then it gets resolved when all the promises get resolved or any one of await Promise.all(requests) .catch(e => console.log(`Error in sending� Promise.all takes an array of promises (it technically can be any iterable, but is usually an array) and returns a new promise. The new promise resolves when all listed promises are settled, and the array of their results becomes its result. For instance, the Promise.all below settles after 3 seconds, and then its result is an array [1, 2, 3]:


All you need to know about Promise.all, On some pages, we needed to wait for multiple API requests to complete The Promise.all() method accepts an array of promises, and let's you run You could make your API calls in a sequence, cache the response of each one to a I send out a short email each weekday with code snippets, tools,� Promises in JavaScript are one of the powerful APIs that help us to do Async operations. Promise.all takes Async operations to the next new level as it helps you to aggregate a group of promises.


Waiting for multiple all API responses to complete with the vanilla JS , The API requests are fulfilled with JavaScript promises. In other words, make it so the Promise.all isn't rejected when one or more of the API requests are rejected. If we want to return something other than undefined , we can modify the Make a Press and Hold 'Fast Forward' Button in SwiftUI � How to� Promise.all and Promise.sequence is invoked the same way, but have different semantics. Caution. Sequential running of promises is not usually a very good way to use promises. It's usually better to use Promise.all, and let the browser run the code as fast as possible.