悬赏问答
0回答 463查看
悬赏 1 金币
Chinaboys
描述:后台同学调用第三方接口拿到数据给前端渲染页面,问题是后台数据没有及时同步到位。故此要求前端对接口执行轮询。{首次请求数据未同步过来时,执行setInterval 2s一次 3次},
这样写有什么问题吗?或是朋友有简洁的代码供学习下。谢谢大佬。
或是对此情况有更好的方案 求指点。
代码如下:
  1. const loadPacketInfo= () => {
  2.     return new Promise((resolve, reject) => {
  3.         getPacketApi()
  4.             .then((result) => {
  5.                 resolve(result);
  6.             })
  7.             .catch((err) => {
  8.                 resolve({});
  9.             });
  10.     });
  11. };
复制代码
  1. //queryAction 触发操作
  2. const queryAction = () => {
  3.     Toast.loading({
  4.         message: '加载中...',
  5.         duration: 0,
  6.         forbidClick: true,
  7.     });

  8.     loadPacketInfo().then((res) => {
  9.         const { data, errno } = res;
  10.         if (errno === '0') {
  11.             if (data.mixedData && data.mixedData.length === 0) {
  12.                 let num = 0;
  13.                 const timer = setInterval(() => {
  14.                     num++;
  15.                     if (num > 3) {
  16.                         Toast.clear();
  17.                         clearInterval(timer);
  18.                         return;
  19.                     }
  20.                     loadPacketInfo().then((result) => {
  21.                         const { data } = result;
  22.                         if (data.mixedData && data.mixedData.length > 0) {
  23.                             updateWrap(data.mixedData);
  24.                             Toast.clear();
  25.                             clearInterval(timer);
  26.                         }
  27.                     });
  28.                 }, 2000);
  29.             } else {
  30.                 if (data.mixedData && data.mixedData.length > 0) {
  31.                     updateWrap(data.mixedData);
  32.                     Toast.clear();
  33.                 }
  34.             }
  35.         }
  36.     });
  37. };
复制代码


快速回答
您需要登录后才可以回帖 登录 | 注册
Smilies Code
高级模式