我有一个非常大的数组(10K),我想拆分它(我按照这个:https : //stackoverflow.com/a/8495740/2183053 并且它有效)但我需要通过 tempArray 来请求并等待用于将传递给 savetodb 的响应。
有人可以帮帮我吗?为了清楚起见,我想拆分大数组并将分离的数组传递给请求函数,然后传递给保存到 db 并继续这个过程,直到所有数组都被清除。
以下是我做的代码:
//i used waterfall because it worked in waiting to finish the first task before starting another
async.waterfall([
async.apply(handleFile, './jsonFile.json')
runRequest1,
savetoDb
], function(err) {
console.log('waterfall1 complete')
})
function handleFile(data, callback) {
var name
var authorNames = []
require('fs').readFile(data, 'utf8', function(err, data) {
if (err) throw err
var content = _.get(JSON.parse(data), [2, 'data'])
for (var x = 0; x < content.length; x++) {
authorNames.push(JSON.stringify(content[x]['author']))
}
//the large array is authorNames and im splitting it below:
for (i = 0, j = authorNames.length; i < j; i += chunk) {
temparray = authorNames.slice(i, i + chunk);
setTimeout(function() {
callback(null, temparray)
}, 2000);
}
})
}