function foo(param) { return new Promise((resolve, reject) => { setTimeout(() => { try { JSON.parse('{{'); // 執行到這裏會報錯 return resolve(param); } catch (err) { return reject(err); } }, 1000); }); }
async function autoRetry(retryMax) { try { if (retryMax <= 0) { return 'error'; } let res = await foo(1) return res; } catch (error) { return autoRetry(retryMax - 1); } } autoRetry(3) .then(result => { console.log('result', result.data); }) .catch(err => { console.log('err', err); });
foo函數是用來模擬請求的,返回promise對象
正式用法以下:javascript
const axios = require('axios'); /** * 接口請求重試 * @param {num} retryMax 請求次數 */ async function autoRetry(retryMax) { try { if (retryMax <= 0) { return 'error'; } let res = await axios.get('http://dfsports_h5.dftoutiao.com/dfsports_h5/newspool?type=nba&typecode=900047&pgnum=1') return res; } catch (error) { return autoRetry(retryMax - 1); } }
await axios.get()這個方法還能夠封裝一下,用參數傳遞,能夠應對不一樣的請求方法.
也能夠引入node-retry ,retry等...java