0

I'm trying to do the following. Get number of pages from the API. Each page has multiple results. I check all the results with my condition. If the result fits the condition, then I need to finish the check, finish the page search and pass the result to another function. I don't understand how to end ajax (getData() execution in the checkPages() function) and exit the for loop in the same place. The break and return keywords do not help. Please tell me how to do it. Maybe I need to do to refactor my code. I don't really like to "throw" results from a function into a function. I do not use async/await because I need compatibility with old browsers.

getData("url-to-get-data").done(function (result) {
    checkPages(result.total_pages);
});

function getData(url) {
    return $.get({
        url: "url-to-get-data"
    })
}

function checkPages(pagesCount) {
    for (var i = 2; i <= pagesCount; i++) {
        getData("url-to-get-data", i).done(function(result) {
            var today = checkToday(result);
            if (today != null) {
                //someMethod
                //how to end the getData function and the for loop
            }
        });
    }
}

function checkToday(response) {
    var results = response.results;
    var today = new Date();
    var day = today.getDate();
    var month = today.getMonth();
    for (var i = 0; i < results.length; i++) {
        var d = new Date(results[i].release_date);
        if (d.getDate() === day && d.getMonth() === month) {
            return results[i];
        }
    }
    return null;
}

2
  • That's because you're doing ajax requests in a loop... they are asynchronous and you'll not get the result you want like this because by the time your first request completes I'm sure your loop finishes.. Please look around StackOverflow for similar issues as there's plenty. Commented Aug 21, 2018 at 11:27
  • you'll need to ensure you make the requests in series - as of now, all requests are "initiated" before any "checks" can be performed Commented Aug 21, 2018 at 11:29

3 Answers 3

2

simplest change to your checkPages function

inner function that calls itself as required

function checkPages(pagesCount) {
    function checkPage(i) {
        if (i <= pagesCount) {
            getData("url-to-get-data", i).done(function(result) {
                var today = checkToday(result);
                if (today == null) { // only get next page if today is null
                    checkPage(i+1);
                }
            });
        }
    }
    checkPage(2);
}
Sign up to request clarification or add additional context in comments.

2 Comments

You wrote in the comments: don't get the next page. How can this be done for example? Please tell me how to do it right. Where it is clear and well described.
erm I wrote dont' get next page ... because it doesn't - there is no mystery ... modified the code
1

If I understand correctly you are trying to do something like this?

UPDATE: implemented que to check if request is finsihed

getData("url-to-get-data").done(function (result) {
    checkPages(result.total_pages);
});

function getData(url) {
    return $.get({
        url: "url-to-get-data"
    })
}

function checkPages(pagesCount) {
    let doContinue = true;
    let loading = false;
    let i = 2;
    var checker = setTimeout(()=>{
      if(i > pagesCount) clearTimeout(checker);
      if(!loading){
          loading = true;
          getData("url-to-get-data", i).done(function(result) {
            var today = checkToday(result);
            if (today != null) {
                clearTimeout(checker);
            }
            i++;
            loading = false;
        });
      }
    },100);
}

function checkToday(response) {
    var results = response.results;
    var today = new Date();
    var day = today.getDate();
    var month = today.getMonth();
    for (var i = 0; i < results.length; i++) {
        var d = new Date(results[i].release_date);
        if (d.getDate() === day && d.getMonth() === month) {
            return results[i];
        }
    }
    return null;
}

5 Comments

your code will also queue up all the requests before even the first is checked for if (today != null) {
@Domenik Reitzner it certainly doesn't help. Actually the word break in this place can not be put.
@starmucks, yes forgot to remove that one.... had it also in the right place :) Pls see the update
@JaromandaX thank you very much for your help. I would also like to know how to perform such work correctly, in accordance with best practices. Will it help in this case, "promises with the()"?
@Domenik Reitzner thanks, but another solution seems more elegant.
0

Make your ajax call synchronous or use callback functions to keep getting more data until conditions are met.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.