Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

javascript - Make repeated ajax calls inside loop until condition is met

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

{
  data {
    field1 : "value1",
    field2: "value2",
  },
  paginationKey : {
    id: "value for id",
    some_other_field: "value for other field"
  }
}

The value for the pagination key is specified in the request, and the response value for pagination key becomes the pagination key for the next request. The value for pagination key will be null for the first request, and the final value of pagination key in the response will be null. So essentially I have to call the API with pagination key value of null, then whatever value of pagination key I get in response, use that for second request and keep continuing until the value of the key in the response becomes null.

My problem is I am making ajax call using JQuery to this API like

let 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(function(data) {
  successCallBack(data);
}, function(error, errorMessage) {
  failureCallBack(error, errorMessage)
})

with successCallBack and failureCallBack being methods that I have defined

Now the Ajax call, and the subsequent callbacks being asynchronous in JS, I am having difficulty to make these requests in a loop, and break out of this loop when the response paginationKey becomes null. How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...