[英]How to retry api calls using node-fetch
我正在嘗試在我的節點 js 代碼中使用 node-fetch 向外部 API 發布請求。
如果在執行 POST 請求時出現任何超時或網絡故障,我想重試該請求 3 次。
你能告訴我如何使用 node-fetch 重試請求嗎? 我看到有一個 npm 模塊https://www.npmjs.com/package/node-fetch-retry但它似乎沒有按預期工作,而且它也不接受重試之間的重試間隔。 任何代碼片段都會非常有幫助。
編輯:
謝謝我嘗試使用 promise-fn-retry 但它似乎沒有做任何重試。 下面是我通過關閉 WIFI 然后執行 FETCH 調用以查看它是否重試 3 次的代碼片段。 但它只執行一次獲取並返回錯誤。
const promiseFn = () => fetch(url,{method:"POST",headers:header,body:JSON.stringify(payload)});
const options = {
times: 3,
initialDelay: 100,
onRetry: (error) => {
console.log(error);
}
};
console.log('PromiseFn result ****'+retry(promiseFn, options).then(res => res.json()).then((res)=>{console.log('Promise Fn result is'+JSON.stringify(res))}).catch((err)=>{console.log('Error in Promise Fn'+err)}));
這個片段在過去幫助了我! 希望這是你正在尋找的
const fetch = require('node-fetch')
const delay = ms => {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, ms)
})
}
const retryFetch = (url, fetchOptions = {}, retries = 3, retryDelay = 1000, timeout) => {
return new Promise((resolve, reject) => {
// check for timeout
if(timeout) {
setTimeout(() => {
reject('error: timeout') // reject if over time
}, timeout)
}
const wrapper = n => {
fetch(url, fetchOptions)
.then(res => { resolve(res) })
.catch(async err => {
if(n > 0) {
// console.log(`retrying ${n}`)
await delay(retryDelay)
wrapper(--n)
} else {
reject(err)
}
})
}
wrapper(retries)
})
}
retryFetch('http://localhost:8080/test', {}, 20)
.then(res => res.text())
.then(console.log)
.catch(console.error)
試試promise-fn-retry包,它具有指定重試次數、初始延遲時間和回調方法來處理失敗的獲取/承諾的屬性。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.