title: Await async functions to be done in reduce() function
body: <p>I have a fuction which includes the following:</p>
  
  <pre><code>const newThreads = newItems.reduce( (acc, item) =&gt; {
    request(item.href, function(error2, response2, html2){
  
      if(!error2) {
  
        const thread = cheerio.load(html2)
        const today = thread('div#ignmsgbttns1').parent().parent().find("b:contains('Today')")
  
        if(today.text()) {
          acc.push(item)
        }
  
      }
    })
    return acc
  }, [])
  
  console.log(newThreads)
  </code></pre>
  
  <p>Of course the log returns an empty array, because of the async stuff 
  (<code>request</code>)  executed in the <code>reduce</code> loop.</p>
  
  <p>So what I would like to do is:</p>
  
  <pre><code>const newThreads = await newItems.reduce( etc...
  </code></pre>
  
  <p>And wait for the <code>requests</code> in the <code>reduce</code> loop to be done.</p>
  
  <p>But I don't get my head around how to do it properly.</p>
  
  <p>So I know I have to use <code>async</code>, <code>await</code> or <code>promises</code>, but don't know how to do it.</p>
  
  <p>I think the <code>reduce callback</code> also has to be <code>async</code> but absolutely not sure on this point.</p>
  
  <p>The <code>request</code> method comes from the <a href="https://www.npmjs.com/package/request" rel="nofollow noreferrer">npm request package</a> , they also provide some <a href="https://www.npmjs.com/package/request#promises--asyncawait" rel="nofollow noreferrer">packages</a> to use promises, but to be honest, I don't know how to apply it with <code>reduce</code>.</p>
  
  <p>I'm pretty sure there is already a similar question somewhere but couldn't find it.</p>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>ps: for those wondering what cheerio is, here the <a href="https://www.npmjs.com/package/cheerio" rel="nofollow noreferrer">link</a>.</p>
  
  <p><strong>Final code after applying answer</strong></p>
  
  <p>I had to use the <a href="https://www.npmjs.com/package/async-request" rel="nofollow noreferrer">async-request package</a></p>
  
  <pre><code>const newThreads = newItems.reduce(async (acc, item) =&gt; {
    const current = await acc;
  
    const html2 = await requestAsync(item.href);
    const thread = cheerio.load(html2.body);
  
    const today = thread('div#ignmsgbttns1')
      .parent()
      .parent()
      .find("b:contains('Today')");
  
    if (today.text()) current.push(item);
  
    return current;
  }, []);
  
  newThreads.then((res) =&gt; {  
    //..doing stuff with res 
  })
  </code></pre>