Make repeated ajax calls inside loop until condition is met

前端 未结 1 1834
南方客
南方客 2020-12-21 22:31

I am calling an API which has pagination implemented. The response from the API is

{
  data {
    field1 : \"value1\",
    field2: \"value2\",
  },
  paginat         


        
相关标签:
1条回答
  • 2020-12-21 22:52

    Since you need to wait for a call to finish before initiating a new call, you can use a standard loop. A simple solution is to call the API once a call is done, and the key is not null:

    const repeatedAPICall = (requestData, successCallBack, failureCallBack) => {
      const ajaxPromise = $.ajax({
        url: requestUrl,
        type: 'GET',
        data: requestData, // containing the paginationKey like I mentioned above
        // other parameters for AJAX call like crossdomain, timeout etc
      })
    
      ajaxPromise.then((data) => {
        successCallBack(data)
    
        if(data.paginationKey) {
          repeatedAPICall(data.paginationKey, successCallBack, failureCallBack)
        }
      }, (error, errorMessage) => {
        failureCallBack(error, errorMessage)
      })
    }
    
    // 1st call
    repeatedAPICall(null, successCallBack, failureCallBack)
    

    If you need an array of pages, you can use async/await in a for...of loop. For every key that is not null, we add the key to the array. If there's a key in the array, we make an api call, and add the result to the results array.

    async function repeatedAPICall(
      apiCall,
      startValue
    ) {
      const keys = [startValue];
      const result = [];
    
      for (const callKey of keys) {
        const data = await apiCall(callKey);
    
        result.push(data);
    
        if (data.key !== null) keys.push(data.key);
      }
    
      return result;
    }
    
    // mock api call
    const apiCall = ((counter) => () => Promise.resolve({
      key: counter < 5 ? counter++ : null
    }))(0);
    
    repeatedAPICall(apiCall, null)
      .then(result => console.log(result)); // use your callbacks here

    0 讨论(0)
提交回复
热议问题