在异步函数中使用setTimeout

Mat*_*ean 2 javascript asynchronous settimeout async-await axios

我有一个异步函数,在继续之前等待axios调用完成.问题是我需要将axios调用的超时时间设置为半秒,这样我才能达到shopify API调用限制.

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)
}
Run Code Online (Sandbox Code Playgroud)

当我尝试设置setTimeout时,它会调用setTimeout并在完成axios调用之前继续.

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)
}
Run Code Online (Sandbox Code Playgroud)

有帮助吗?

SLa*_*aks 8

await只适用于承诺.你需要包含setTimeout一个承诺:

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

await waitFor(500);
Run Code Online (Sandbox Code Playgroud)


Lan*_*ley 6

创建一个sleep返回可以使用的 Promise 的函数,如下所示:

const sleep = (milliseconds=500) => new Promise(resolve => setTimeout(resolve, milliseconds))
Run Code Online (Sandbox Code Playgroud)

并在异步函数中使用它:

(async () => {
  console.log("function invoked...")
  await sleep(500)
  console.log("I got here about 500 milliseconds later")
})()
Run Code Online (Sandbox Code Playgroud)


Ala*_*man 5

setTimeout 不返回承诺,因此不能被await编辑。

您可以创建自己的基于 PromisesetTimeout并使用它。

const setTimeoutPromise = timeout => new Promise(resolve => {        
  setTimeout(resolve, timeout);
});

await setTimeoutPromise(500);
Run Code Online (Sandbox Code Playgroud)


Pat*_*rts 5

setTimeout()不会返回Promise,但是您可以将其包装成这样。我还清理了其余的代码。

async function processMatchingSchools(customer_metafield_url) {
  for (const item of customer_metafield_url) {
    await new Promise(resolve => {
      setTimeout(resolve, 500)
    })

    await axios.get(item).then((res) => {
      Object.values(res.data.metafields).filter(
        ({ value }) => value === schoolName
      ).forEach(({ owner_id }) => {
        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)
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢大家帮助我:P 感谢帕特里克帮助我清理我的新手代码。 (2认同)