简体   繁体   English

打破Node.js / Express.Js中的无限循环

[英]Breaking an infinite loop in Node.js/Express.Js

I've created an Express app that is supposed to be paginating through an external API call. 我创建了一个Express应用程序,该应用程序应该通过外部API调用进行分页。 I've looked at this every which way and I can't figure out why the function isn't tripping the condition to break the loop. 我已经以各种方式研究了这个问题,但我不知道为什么该函数没有触发条件来破坏循环。 Any help would be appreciated! 任何帮助,将不胜感激!

Looks like I can't break from the last loop, calling the makeRequest function. 看起来我不能中断上一个循环,调用makeRequest函数。 Evidence for the infinite loop is the first console.log in the request callback, "I'm making a request." 无限循环的证据是请求回调中的第一个console.log,“我正在发出请求”。 I had more console.logs further down in the callback function that should also always return something but it doesn't even seem to get to those. 我在回调函数的后面还有更多console.logs,它也应该总是返回某些内容,但似乎并没有返回这些内容。

app.post("/api/example", function(req, res) {
    var username = username;
    var password = password;
    var container = [];
    var counter = 0;
    var keepGoing = true;

    var makeRequest = function() {
        console.log("I'm making a request");
        var URL = "https://fakeapiurl.com/&page=" + counter; 
        request.get(URL, { 
            'auth': {
                'user': username, 
                'pass': password,
                'sendImmediately': true
            },
            'content-type': 'application/json'
            }, function(error, response, data) {
                var results = JSON.parse(data);
                var examples = results.examples;
                var numOfExamples = results.numResults;
                console.log(numOfExamples);

                if ((numOfExamples === 0) || (numOfExamples === jobsContainer.length - 1)) {
                    counter = 5;
                    keepGoing = false;
                } else {
                    counter++;
                    for (var i = 0; i < examples.length; i++) {
                    container.push(examples[i]);
                    }
                } 

                if (counter === 5) { 
                    keepGoing = false;
                    container.sort(function(a, b) {
                        etc.
                    });

                    res.send(container); 
                }
            });// end of request call 
        };// end of makeRequest function

    while (keepGoing === true) {
        makeRequest();
    }

});// end of app post

This will never work like you would expect, you're firing async requests inside a sync while loop. 这将永远不会像您期望的那样工作,您将在sync while循环内触发异步请求。 So at the time the first request is trying to get the data, you're firing the same request again, so your first request gets canceled. 因此,在第一个请求尝试获取数据时,您将再次触发同一请求,因此您的第一个请求被取消。 This goes like forever. 这就像永远。 You should fire the next request inside the success callback of the previous request, so it gets fired after the previous one resolves. 您应该在前一个请求的成功回调中触发下一个请求,以便在前一个请求解析后将其触发。

Something like that: 像这样:

app.post("/api/example", function(req, res) {
var username = username;
var password = password;
var container = [];
var maxPages = 5;
var makeRequest = function(page) {
    console.log("I'm making a request");
    var URL = "https://fakeapiurl.com/&page=" + page; 
    request.get(URL, { 
        'auth': {
            'user': username, 
            'pass': password,
            'sendImmediately': true
        },
        'content-type': 'application/json'
        }, function(error, response, data) {
            var results = JSON.parse(data);
            var examples = results.examples || [];
            var numOfExamples = results.numResults;
            var lastPageReached = (numOfExamples === 0 || numOfExamples === jobsContainer.length - 1);
            lastPageReached = lastPageReached  && page < maxPages;

            if (lastPageReached) {
                container.sort(function(a, b) {
                    etc.
                });
                res.send(container); 
            } else {
                container = container.concat(...examples);
                makeRequest(page + 1);
            } 
        });
    };
  makeRequest(0);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM