Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 398
Matthew Werdean Avatar asked Jul 05 '18 22:07

Matthew Werdean


People also ask

How can we execute setTimeout in an async way?

Working with asynchronous functionssetTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.

How setTimeout works asynchronously under the hood?

every function that is asynchronous like Ajax, setTimeout, event handlers, etc.., joins the Events table and waits for the time for execution to come for example setTimeout waits 3000 ms to run or event handler waits until Click event happens and then run.

Is set timeout a promise?

setTimeout() is not exactly a perfect tool for the job, but it's easy enough to wrap it into a promise: const awaitTimeout = delay => new Promise(resolve => setTimeout(resolve, delay)); awaitTimeout(300).

Is setTimeout a callback function?

Introduction to JavaScript setTimeout()cb is a callback function to be executed after the timer expires. delay is the time in milliseconds that the timer should wait before executing the callback function.

How to use setTimeout in an async function with JavaScript?

To use setTimeout in an async function with JavaScript, we can create a promise that calls setTimeout. const wait = delay => new Promise (resolve => setTimeout (resolve, delay)); const f = async () => { console.log (1) await wait (2000); console.log (2) } f ()

What is setTimeout and how does it work?

setTimeout accepts a reference to a function as the first argument. This can be the name of a function: A variable that refers to a function (a function expression): Or an anonymous function: As noted above, it’s also possible to pass setTimeout a string of code for it to execute: However, this is not advisable for the following reasons:

Does timeout need to be an async function?

@tinkerr "timeout needs to be declared async if it needs to be awaited" - Nope. A function only needs to return a promise that can be awaited (or actually, a thenable is enough). How it achieves that is up to the implementation of the function, it does not need to be an async function. @naisanza No, async / await is based on promises.

How to use setTimeout with ES7 async-await?

setTimeout is not an async function, so you can't use it with ES7 async-await. But you could implement your sleep function using ES6 Promise: function sleep (fn, par) { return new Promise ( (resolve) => { // wait 3s before calling fn (par) setTimeout ( () => resolve (fn (par)), 3000) }) }


1 Answers

await only works on promises. You need to wrap setTimeout in a promise:

const waitFor = delay => new Promise(resolve => setTimeout(resolve, delay));

await waitFor(500);
like image 51
SLaks Avatar answered Oct 11 '22 21:10

SLaks