title: Waiting for Promises to resolve within an Array
body: <p>With an <strong>Array</strong> of <strong>Promises</strong> how do I wait until they have all resolved before proceeding?</p>
  
  <p>Below is an example implementation, where <code>task_2</code> is firing it's rejection before <code>task_1</code> can trigger.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const $output = $$('output')
  
  const config = {
    task_1: [
      val =&gt; new Promise((resolve, reject) =&gt; setTimeout(() =&gt; reject('Awaited error'), 2000)),
      val =&gt; new Promise((resolve, reject) =&gt; resolve(val))
    ],
    task_2: [
      val =&gt; new Promise((resolve, reject) =&gt; resolve(val)),
      val =&gt; new Promise((resolve, reject) =&gt; reject('An error')),
    ]
  }
  
  taskRunner({
      task_1: 'task parameters',
      task_2: 'task parameters'
    })
    .then(res =&gt; $output.text(res).fadeIn())
    .catch(err =&gt; $output.text(err).fadeIn())
  
  function taskRunner(tasks) {
    return new Promise((resolve, reject) =&gt; {
      let arr = []
      for (const task in tasks) {
        if (!config.hasOwnProperty(task)) return reject(`${task} has no tasks`)
        arr.push(config[task].map((cb =&gt; cb(tasks[task]))))
      }
  
      const toRun = arr.reduce((a, b) =&gt; a.concat(b))
      Promise.all(toRun)
        .then(res =&gt; resolve(res))
        .catch(err =&gt; reject(err))
    })
  }
  
  function $$(data) {
    return $('[data-' + data + ']')
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { margin: 0; padding: 0 }
  div.output {
    font-family: 'Courier', monospace;
    color: #383838;
    margin: 15px;
    padding: 15px 20px;
    background: #fafafa;
    border-radius: 3px;
    border-bottom: 1px solid #dadada;
  }
  .js-hide { display: none }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;div class="output js-hide" data-output&gt;&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>