I am using a restful API, and I need to post some data. but before, I need to ensure that the table is empty. The problem I am facing is that the delete method of this API return success, but does not immediately delete the data, this data is sent to a queue to delete asap.
So before I call the post method, I need to check if I have any items on this table. How can I call this method several times to ensure that the post method will only be executed when the table is empty?
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
}
The methods:
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()
}
CodePudding user response:
You need to make a recursive call with an exit condition that asks it to exit when the number of elements is 0.
One way could be something like this:
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));
}
Instead of deleting constantly, you might as well just poll to see if the server has completed the original delete:
async function checkIsEmpty() {
const items = await getItems();
if (items.length) {
return checkIsEmpty();
}
}
async function deleteAndPollUntilEmpty() {
await apiDelete();
await checkIsEmpty();
}
async function run() {
await deleteAndPollUntilEmpty();
apiPost()
.then(() => console.log("posting..."))
.catch((e) => console.log(e));
}