我有一个非常大的数组(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);
}
})
}
&#13;
答案 0 :(得分:1)
你需要承诺在nodejs中处理异步事件
let findAllReceipts = function (accountArray) {
const a = [];
for (let i = 0; i < accountArray.length; i++) {
a.push(new Promise((resolve, reject) => {
receiptTable.find({accountNo: accountArray[i].accountNo}, function (err, data) {
if (!err) {
resolve(data);
} else {
reject(new Error('findPrice ERROR : ' + err));
}
});
}));
}
return Promise.all(a);
};
答案 1 :(得分:1)
我添加了一些承诺。
const data = await handleFile('./jsonFile.json');
// save to db
async function handleFile(filePath) {
let arrayWillReturn = [];
var name
var authorNames = []
let data = await getFileData(filePath)
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) {
arrayWillReturn.push(authorNames.slice(i, i + chunk));
}
return arrayWillReturn;
}
async function getFileData(fileName) {
return new Promise(function (resolve, reject) {
fs.readFile(fileName, type, (err, data) => {
err ? reject(err) : resolve(data);
});
});
}
答案 2 :(得分:0)
我回答了我自己的问题以备将来参考。我为使代码工作而添加的唯一内容是Promise。这听起来很容易,但我花了一些时间来掌握功能并实现它,但它有效并且值得。非常感谢您的回复。