无法在callback函数上进行分页

我试图分页的callback函数调用,但得到第二个电话的错误

我的function是:

let content = '' let size = 100 let from = 1 function result(size, from, callback) { api.performRequest('/myContents', 'GET', { pageSize: size, startFrom: from, filter:'NOT contents:[* TO *]', }, function (data) { content += JSON.stringify(data) callback() }) } function logContent() { const parsed = JSON.parse(content) console.log('content length: ', parsed.body.length) if (parsed.body.length === size) { calculate(size, from + size) } } function calculate(size, from) { result(size, from, logContent) } calculate(size, from) 

在第一次调用控制台返回

内容长度:100

在第二个电话上,我得到了我日志上的所有JSON块和一个错误

意外的标记{在位置32847的JSON中

我认为这与callback和函数完成前发生的事情有关,但我无法看到我在这里做错了什么

函数performRequest只是做一个http get并返回一个json块

 export function performRequest(endpoint, method, data, callback) { const headers = { Authorization: auth, 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Expose-Headers': 'Location,ETag', } let options = { host: host, port: port, path: endpoint, headers: headers, } if (method === 'GET') { endpoint += '?' + queryString.stringify(data) const additionalOptions = { path: endpoint, } options = _.merge(options, additionalOptions) } return http.get(options, function (response) { // Continuously update stream with data let body = '' response.on('data', function (d) { body += d }) response.on('end', function () { // Data reception is done const parsed = JSON.parse(body) callback({ totalCount: parsed.totalCount, body: parsed.content, }) }) }) } 

你的第一个电话会很好,因为你的内容最初是空的。 所以,在第一次通话中:

 content = '' --> content = '{...}' 

而你的第二个电话:

 content = '{...}' --> content = '{...}{...}' 

因此错误:

意外的标记{在位置32847的JSON中

您需要将每个对象放在一个数组中,或者如果您希望它能够工作,则甚至可以放在另一个对象中。 您可以创build一个数组,并在每次调用时push每个元素都push送到其中。