Search code examples
javascriptpromisees6-promise

How to execute promises in order and return all results


I am new to promises. I have looked up examples of executing promises in order, but I haven't found an example that is similar to my application.

My problem is that I want to resolve promises in a certain order, but also capture all the results when the promises resolve. From looking up examples. I have created a simplified version of the problem.

I was able to create a function doWork(), but the problem is that all it does is resolve promises in order, without capturing results.

Ideally, I want a function that returns a promise which resolves with all the results.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Test</title>
   <script>
      function getRandomInterval(min, max){
         var random = Math.random() * (+max - +min) + +min;
         return random;
      }

      function createPromiseReturningFn(input){
         return function(){
            return new Promise(
               function(resolve, reject){
                  setTimeout(function(){
                     // console.log(input);
                     resolve(input);
                  }, getRandomInterval(0, 100));
               }
            );
         }
      }

      var promises = [];

      for (var i=0; i<10; i++){
         promises.push(createPromiseReturningFn(i));
      }

      function doWork(){
         if (!promises.length)
            return;
         var promise = promises.shift();
         promise().then(
            doWork
         );
      }

      doWork();
   </script>
</head>
<body>

</body>
</html>

Solution

  • Try using an async function and iterating over the promises in a for...of loop:

    Resolve promises one after another (i.e. in sequence)?