简版—await

  1. export const sleep = (timeout = 100) => {
  2. return new Promise(resolve => {
  3. setTimeout(resolve, timeout)
  4. })
  5. }
  6. // 轮询函数
  7. const polling = async (request, times) => {
  8. if (times <= 0) {
  9. return false;
  10. }
  11. const result = await request();
  12. if (result) {
  13. return true;
  14. }
  15. await sleep(1000);
  16. return polling(request, times - 1);
  17. };
  18. // 请求主体函数
  19. const checkOrder = async orderSn => {
  20. const {
  21. data: { status },
  22. } = await Axios.get('/mall/order/status', {
  23. params: { orderSn },
  24. })
  25. return status === 2
  26. }
  27. // 调用
  28. // 当请求主体函数返回true或者times跑完时候会终止
  29. const status = await polling(() => checkOrder(appOrderSn), 3)