我正在使用restful,我需要发布一些数据。但在此之前,我需要确保桌子是空的。我面临的问题是,该API的delete方法返回成功,但没有立即删除数据,该数据被发送到队列中以尽快删除。
因此,在调用post方法之前,我需要检查一下这张桌子上是否有任何项目。如何多次调用此方法以确保只有在表为空时才会执行post方法?
async function run() {
apiDelete()
.then(() => console.log('deleting'))
.then(() => {
getItems().
then(() => {
apiPost()
.then(() => console.log('posting...'))
.catch(e => console.log(e))
})
})
.catch(e => console.log(e))
return
}方法:
async function apiPost() {
const url = 'https://apipost.com/data/v2/1234'
const options = {
method: 'POST'
}
return (await fetch(url, options)).json()
}
async function apiDelete() {
const url = 'https://apidelete.com/data/v2/all'
const options = {
method: 'DELETE',
}
return (await fetch(url, options)).json()
}
async function getItems() {
const url = 'https://apiget.com/data/v2/all'
const options = {
method: 'GET',
}
return (await fetch(url, options)).json()
}发布于 2022-02-15 20:57:34
您需要使用退出条件进行递归调用,当元素数为0时,该条件要求退出。
一种方法可能是这样的:
async function deleteUntilEmpty() {
await apiDelete();
const items = await getItems();
if (items.length) {
return deleteUntilEmpty();
}
}
async function run() {
await deleteUntilEmpty();
apiPost()
.then(() => console.log("posting..."))
.catch((e) => console.log(e));
}与其不断删除,不如直接轮询服务器是否完成了原始删除:
async function pollUntilEmpty() {
const items = await getItems();
if (items.length) {
// this could be a good spot to introduce some kind of
// sleep to not DDOS your server ;)
return pollUntilEmpty();
}
}
async function deleteAndPollUntilEmpty() {
await apiDelete();
await pollUntilEmpty();
}
async function run() {
await deleteAndPollUntilEmpty();
apiPost()
.then(() => console.log("posting..."))
.catch((e) => console.log(e));
}https://stackoverflow.com/questions/71133275
复制相似问题