gpt4 book ai didi

javascript - 在异步函数中使用 setTimeout

转载 作者:行者123 更新时间:2023-12-01 14:55:39 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Combination of async function + await + setTimeout

(15 个回答)


7 天前关闭。




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

有什么帮助吗?

最佳答案

await仅适用于 promise 。
您需要包装 setTimeout在 promise 中:

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

await waitFor(500);

关于javascript - 在异步函数中使用 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51200626/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com