使用递归函数
由于您不知道偏移量限制是您对大量请求的最佳猜测,因此您将更快地达到您的偏移量。
对于异步任务,我喜欢使用 async here。这是一个例子:
const async = require('async')
const offsets = [0, 50, 100, 150];
async.map(offsets, function (offset, callback) {
// Do request here with 'offset'
// And return response in the callback
// Do not return an error, otherwise the main callback (of map function)
// will be called immediately
return callback (null, response);
}, function (error, results) {
// results is an array containing all responses from all requests
// iterate over results, if all contain a valid result,
// you can increase your offset group and perform this operation again
});
当然,您需要将其包装到另一个允许增加 offsetgroup 的函数中,只要您获得有效结果就重复请求 -> 所谓的 递归函数:
const async = require('async')
function performGroupRequest (offsets, allResults, end) {
async.map(offsets, function (offset, callback) {
// Do request here with 'offset' and return response in the callback
return callback (null, response);
}, function (error, results) {
// check results
results.map(r => {
if (hasItems(r)) {
// valid result, add to allResults
allResults.push(r);
} else {
// invalid result, let's end here
return end(allResults);
}
});
// all results are valid here, so call the function again, with increased offset
performGroupRequest(offsets.map(o => o + 200), allResults, end)
});
}
function getAllItems () {
return Promise((resolve, reject) => {
performGroupRequest([0, 50, 100, 150], [], function(all) {
return resolve(all);
});
});
}
// start the journey
getAllItems().then((allResults) => {
});
? 请注意:为了简单起见,我在这里完全省略了错误处理。