3 回答

TA貢獻1828條經驗 獲得超4個贊
您的代碼中有很多重復項。為了減少代碼重復,您可以創建一個可以使用適當參數調用的輔助函數,該輔助函數將包含刪除產品線和產品的代碼。
async function deleteHelper(getURL, deleteURL) {
const response = await axios.get(getURL);
const ids = response.data.value;
return Promise.all(ids.map(id => (
axios.delete(deleteURL + id)
)));
}
有了這個輔助函數,現在您的代碼將得到簡化并且沒有代碼重復。
現在要達到預期的結果,您可以使用以下方法之一:
不要使用兩個單獨的承諾鏈,而只使用一個刪除產品線然后刪除產品的承諾鏈。
const prodLineGetURL = 'https://myapi.com/ProductLine?select=id';
const prodLineDeleteURL = 'https://myapi.com/ProductLine/';
deleteHelper(prodLineGetURL, prodLineDeleteURL)
.then(function() {
const prodGetURL = 'https://myapi.com/Product?select=id';
const prodDeleteURL = 'https://myapi.com/Product/';
deleteHelper(prodGetURL, prodDeleteURL);
})
.catch(function (error) {
// handle error
});
使用async-await語法。
async function delete() {
try {
const urls = [
[ prodLineGetURL, prodLineDeleteURL ],
[ prodGetURL, prodDeleteURL ]
];
for (const [getURL, deleteURL] of urls) {
await deleteHelper(getURL, deleteURL);
}
} catch (error) {
// handle error
}
}
您可以在代碼中改進的另一件事是使用Promise.all而不是forEach()方法來發出刪除請求,上面的代碼使用Promise.all內部deleteHelper函數。

TA貢獻1860條經驗 獲得超8個贊
您的代碼(以及所有其他答案)正在delete按順序執行請求,這是對時間的巨大浪費。Promise.all()您應該并行使用和執行...
// Delete Product Lines
axios.get('https://myapi.com/ProductLine?select=id')
.then(function (response) {
const ids = response.data.value
// execute all delete requests in parallel
Promise.all(
ids.map(id => axios.delete('https://myapi.com/ProductLine/' + id))
).then(
// all delete request are finished
);
})
.catch(function (error) {
})

TA貢獻1775條經驗 獲得超11個贊
所有 HTTP 請求都是異步的,但您可以使其類似同步。如何?使用異步等待
假設您有一個名為 的函數retrieveProducts,您需要創建該函數async然后await讓響應繼續處理。
留給:
const retrieveProducts = async () => {
// Delete Product Lines
const response = await axios.get('https://myapi.com/ProductLine?select=id')
const ids = response.data.value
ids.forEach(id => {
axios.delete('https://myapi.com/ProductLine/' + id)
})
// Delete Products (I want to ensure this runs after the above code)
const otherResponse = await axios.get('https://myapi.com/Product?select=id') // use proper var name
const otherIds = response.data.value //same here
otherIds.forEach(id => {
axios.delete('https://myapi.com/Product/' + id)
})
}
但請記住,它不是同步的,它一直是異步的
添加回答
舉報