title: Skip waiting if async function (Promise) is taking too much time
body: <p>In my express application, I am making call to 2 APIs. The 2nd API is managed by 3rd party and sometimes can take more than 5 seconds to respond. Hence, I want to just wait for 1 second for the API to respond. If it does not, just proceed with data from 1st API.</p>
  <p>Below is the mock-up of the functions being called.
  I am thinking to use <code>setTimeout</code> to throw error if the API takes more than 1 second. If the API responds within 1 second then I just cancel the <code>setTimeout</code> and no error is ever thrown.</p>
  <p>But there is problem with this approach:</p>
  <ol>
  <li><code>setTimeout</code> errors cannot be catched using <code>try...catch</code> block.</li>
  </ol>
  <p>I cannot use axios's timeout option, as I still need to wait for the 2nd API to finish the processing and save the data in the DB. This will ofcourse, can happen later, when the 2nd API call finishes.</p>
  <pre class="lang-js prettyprint-override"><code>
  // Function to simulate it's taking time.
  async function cWait(ms) {
    return new Promise(resolve =&gt; setTimeout(resolve, ms));
  }
  
  // Track whether it took time.
  let isTimeOut = false
  
  async function test() {
    console.log('starting')
    try {
      const one = await apiCall1()
      const myt = setTimeout(() =&gt; {
        console.log('Its taking time, skip the 2nd API Call')
        isTimeOut = true
        throw new Error('Its taking time')
      })
      const two = await apiCall2(myt)
    } catch (error) {
      console.log(error)
    }
    saveInDB({ ...one, ...two })
  }
  
  
  async function apiCall2(timeOutInstance) {
    console.log('start-apiCall')
    await cWait(1800)
    clearTimeout(timeOutInstance)
    if (isTimeOut) saveInDB()
    console.log('done-apiCall')
  }
  
  async function apiCall1() {
    await cWait(5)
  }
  
  async function saveInDB(data) {
    console.log('saveInDB')
  }
  
  test()
  </code></pre>