我正在使用一個寧靜的 API,我需要發布一些資料。但在此之前,我需要確保表是空的。我面臨的問題是這個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()
}
uj5u.com熱心網友回復:
您需要使用退出條件進行遞回呼叫,要求它在元素數量為 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://www.uj5u.com/net/424026.html
標籤:javascript 节点.js api 获取 API
