Home > Back-end >  TypeScript Promise Series Execution
TypeScript Promise Series Execution

Time:02-23

I've a list of doc objects and there is a need to make a API call for every doc id in the list and want to execute the API calls in a series fashion. Promise.all and Promise.allSelected executes them in a concurrent manner, in Typescript

[
  {
    "doc_id": 11
  },
  {
    "doc_id": 22
  },
  {
    "doc_id": 33
  }
]

Thanks in advance

CodePudding user response:

Iterate over your array, here: documents of type Array<{ doc_id: number }>, to execute them in the given order:

for (const document of documents) {

  const response = await callApi(document['doc_id']);

  // do someting with response
  // or call just await callApi(document['doc_id']);

}

CodePudding user response:

Promise.all and Promise.allSettled will wait for the promises asynchronously and simultaneously, but most API calls start the moment the Promise is created. Consequently, it wouldn't solve your problem to create all the promises at once and then simply await them one by one instead of using Promise.all: You need to defer their creation to happen one by one.

If you want to delay the API call for the second doc, you need to make sure you await the first response before creating the Promise for the second response. (pzaenger's answer does this well.) If you're using then and catch rather than await, you'll need to make sure that the second call to your API happens in the then handler of the first call, and the third in the second, and so forth.

There are also tools to handle the general "throttling" problem, which can ensure that only n unsettled promises coexist at once; doing API calls in sequence is merely the case where n = 1. You might prefer to use a fairly general throttling library here, since you might find it valuable in the future to handle a small finite number at once (n = 3) or throttle by time (e.g. 1 request per second). This would be difficult to implement if you rewrite your code to run serially, but easy to modify with a library.

  • Related