在异步函数中使用 setTimeout [重复]

问题描述 投票:0回答:6

我有一个异步函数,它等待 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)
}

当我尝试放置 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)
}

有什么帮助吗?

javascript asynchronous async-await settimeout axios
6个回答
47
投票

await
仅适用于承诺。 你需要将
setTimeout
包裹在一个承诺中:

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

await waitFor(500);

27
投票

setTimeout()
不会返回
Promise
,但您可以将其包装在这样的一个中。我还稍微清理了你其余的代码。

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)
}

9
投票

setTimeout 不返回承诺,因此无法

await
ed。

您可以创建自己的基于承诺的

setTimeout
并使用它。

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

await setTimeoutPromise(500);

6
投票

创建一个

sleep
函数,返回您可以使用的 Promise,如下所示:

const sleep = (milliseconds=500) => new Promise(resolve => setTimeout(resolve, milliseconds))

并在异步函数中使用它:

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

4
投票

您需要创建新的承诺,例如这样

function delay(ms){
 return new Promise(resolve => setTimeout(resolve, ms))
}

然后在调用 API 之前在代码中使用它

...
await delay(500)
await axios.get(item).then((res) => {
...

3
投票

我创建了

setTimeout2
函数,其工作原理与承诺相同:

const setTimeout2 = (callback, ms) => {
  return new Promise(resolve => setTimeout(() => {
    callback();
    resolve();
  }, ms));
} 

所以,总共(注意 setTimeout2 的变化):

async function processMatchingSchools(customer_metafield_url) {
  for (const item of customer_metafield_url) {
    await setTimeout2(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)
}
© www.soinside.com 2019 - 2024. All rights reserved.