0

We have a array of promises . We have to resolve them in such a way that at a time there should not be more than 3 unresolved promises enter code here

my approach is

const promises = [
  new Promise(function (resolve, reject) {
    resolve();
  }),
  new Promise(function (resolve, reject) {
    resolve();
  }),
  new Promise(function (resolve, reject) {
    resolve();
  }),
  new Promise(function (resolve, reject) {
    resolve();
  }),
];

const bucket = [];

const interval = setInterval(function () {
// Filter the unresolved promises.

  const unresolvedPromises = promises.filter(function (promise) {  
    if (promise.done && promise.done === true) {
      return false;
    }
    return true;
  });

  // Add the unresolved promises in the bucket.

  for (let i = 0; i < 3 - bucket.length; ++i) {
    bucket.push(unresolvedPromises[i]);
  }

  if (unresolvedPromises.length === 0) {
    clearInterval(interval);
  }

  console.log(bucket);

}, 10);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • 1
    You haven't asked a question. Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask). To get the best answers to your question we like to see that you've attempted to solve the problem yourself first using a [mcve]. [Here's a question checklist you might find useful.](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). – Andy Jun 18 '21 at 20:21
  • 1
    Your `const promises` already starts with 4 fulfilled promises, so I don't see what the intention is of the code that follows below it. You cannot make fulfilled promises pending again, ... the exercise is already over before it even started. Also, what is `promise.done`? You never define that property. – trincot Jun 18 '21 at 20:26
  • 1
    Are you trying to ["throttle" the number of promises open at a time](https://stackoverflow.com/q/38385419/1426891)? If so, note that rather than receiving promises your function will need to receive "promise factories" (functions that return promises) such that you can defer creating the promise until you have space to do so. – Jeff Bowman Jun 18 '21 at 21:09
  • You could write a `Pool` as described in [this Q&A](https://stackoverflow.com/a/67628301/633183) – Mulan Jun 19 '21 at 15:20

0 Answers0