javascriptasynchronousasync-awaitsettimeoutaxios

Using a setTimeout in a async function


I have a async function that waits for an axios call to complete before proceeding. The problem is that I need to put a timeout on the axios call to half a second so that I don't hit the shopify API call limit.

async function processMatchingSchools(customer_metafield_url) {
  for (const item of customer_metafield_url) {
    await axios.get(item).then((res) => {
      for (key in res.data.metafields) {
        if (res.data.metafields[key].value === schoolName) {
          id_for_each_student.push(shopifyAdmin + "/customers/" + res.data.metafields[key].owner_id + "/metafields.json")
        }
      }
    })
  }
  console.log("Customer metafields to search", id_for_each_student)
  processOwnerIds(id_for_each_student)
}

when I try putting a setTimeout, it calls the setTimeout and moves on before completing the axios calls.

async function processMatchingSchools(customer_metafield_url) {
  for (const item of customer_metafield_url) {
    await setTimeout(function(item) {
      axios.get(item).then((res) => {
        for (key in res.data.metafields) {
          if (res.data.metafields[key].value === schoolName) {
            id_for_each_student.push(shopifyAdmin + "/customers/" + res.data.metafields[key].owner_id + "/metafields.json")
          }
        }
      })
    }, 500)
  }
  console.log("Customer metafields to search", id_for_each_student)
  processOwnerIds(id_for_each_student)
}

Any help?


Solution

  • setTimeout() doesn't return a Promise, but you can wrap it in one like this. I also cleaned up the rest of your code a little.

    async function processMatchingSchools(customer_metafield_url) {
      for (const item of customer_metafield_url) {
        await new Promise(resolve => {
          setTimeout(resolve, 500)
        })
    
        const { data: { metafields } } = await axios.get(item)
    
        for (const { value, owner_id } of Object.values(metafields)) {
          if (value === schoolName) {
            id_for_each_student.push(`${shopifyAdmin}/customers/${owner_id}/metafields.json`)
          }
        }
      }
    
      console.log("Customer metafields to search", id_for_each_student)
    
      processOwnerIds(id_for_each_student)
    }