1

I'm trying to split an API request with an offset variable in order to have partial results without waiting the end of the entire request. Basically I make an API request for the first 100 values, and then I increase it with 100 more till reach the end. The offset is just the starting point.

/*Node.js connector to Context.io API*/
var key = xxxxxx;
var secret = "xxxxxxxxx";
var inbox_id = "xxxxxxxxx";
var end_loop = false;
var offset = 6000;

/*global ContextIO, console*/
var ContextIO = require('contextio');
var ctxioClient = new ContextIO.Client('2.0', 'https://api.context.io', { key: key, secret: secret });

while(end_loop === false) {
    contextio_request(offset, function(response){
        if (response.body.length < 100) { console.log("This is the end "+response.body.length); end_loop = true; }
        else { offset += 100; }
        console.log("Partial results processing");
    });

};

/* Context.io API request to access all messages for the id inbox */
function contextio_request(offset, callback) {
 ctxioClient.accounts(inbox_id).messages().get({body_type: 'text/plain', include_body: 1, limit: 100, offset: offset}, function (err, response) {
    "use strict";
    if (err) {
        return console.log(err);
    }
    callback(response);
});
};

What I don't understand is why if I change the "while loop" with a "if condition", everything works, but with the "while" it enters in an infinite loop". Also, is it the correct way to make a partial request -> wait for response - > process the response -> follow with next request?

4

1 回答 1

1

while 循环将contextio_request()几乎无限期地调用,因为这会产生一个不会立即返回的异步调用。

更好的方法是编写一个调用 的递归方法contextio_request(),在该方法中检查响应正文长度是否小于 100。

基本逻辑:

function recursiveMethod = function(offset, partialCallback, completedCallback) {
    contextio_request(offset, function(response) {
        if (response.body.length < 100) { 
            completedCallback(...);
        } else {
            partialCallback(...);
            recursiveMethod(offset, partialCallback, completedCallback);
        }
    });
};

另外,发出部分请求->等待响应->处理响应->跟随下一个请求是正确的方法吗?

我看不出为什么不这样做。

于 2013-09-05T13:39:38.240 回答