Make repeated ajax calls inside loop until condition is met









up vote
0
down vote

favorite












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?










share|improve this question





















  • Is this through a public api you can share link to ? Are you wanting all the data pushed into a single array ?
    – charlietfl
    Nov 10 at 15:45










  • Sorry, I can not share the API as it is not public. Yes, I want to store the data in a single array, but also update the result stored inside the array based on the response returned from every call.
    – anuyog
    Nov 10 at 16:27














up vote
0
down vote

favorite












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?










share|improve this question





















  • Is this through a public api you can share link to ? Are you wanting all the data pushed into a single array ?
    – charlietfl
    Nov 10 at 15:45










  • Sorry, I can not share the API as it is not public. Yes, I want to store the data in a single array, but also update the result stored inside the array based on the response returned from every call.
    – anuyog
    Nov 10 at 16:27












up vote
0
down vote

favorite









up vote
0
down vote

favorite











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?










share|improve this question













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?







javascript jquery ajax






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 15:35









anuyog

183




183











  • Is this through a public api you can share link to ? Are you wanting all the data pushed into a single array ?
    – charlietfl
    Nov 10 at 15:45










  • Sorry, I can not share the API as it is not public. Yes, I want to store the data in a single array, but also update the result stored inside the array based on the response returned from every call.
    – anuyog
    Nov 10 at 16:27
















  • Is this through a public api you can share link to ? Are you wanting all the data pushed into a single array ?
    – charlietfl
    Nov 10 at 15:45










  • Sorry, I can not share the API as it is not public. Yes, I want to store the data in a single array, but also update the result stored inside the array based on the response returned from every call.
    – anuyog
    Nov 10 at 16:27















Is this through a public api you can share link to ? Are you wanting all the data pushed into a single array ?
– charlietfl
Nov 10 at 15:45




Is this through a public api you can share link to ? Are you wanting all the data pushed into a single array ?
– charlietfl
Nov 10 at 15:45












Sorry, I can not share the API as it is not public. Yes, I want to store the data in a single array, but also update the result stored inside the array based on the response returned from every call.
– anuyog
Nov 10 at 16:27




Sorry, I can not share the API as it is not public. Yes, I want to store the data in a single array, but also update the result stored inside the array based on the response returned from every call.
– anuyog
Nov 10 at 16:27












1 Answer
1






active

oldest

votes

















up vote
0
down vote













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








share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240489%2fmake-repeated-ajax-calls-inside-loop-until-condition-is-met%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    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








    share|improve this answer


























      up vote
      0
      down vote













      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








      share|improve this answer
























        up vote
        0
        down vote










        up vote
        0
        down vote









        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








        share|improve this answer














        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








        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





        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






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 10 at 16:13

























        answered Nov 10 at 15:43









        Ori Drori

        72k127589




        72k127589



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240489%2fmake-repeated-ajax-calls-inside-loop-until-condition-is-met%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kleinkühnau

            Makov (Slowakei)

            Deutsches Schauspielhaus