0

我有一个非常大的数组(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);
    }
  })
}

4

3 回答 3

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);
};
于 2018-05-31T04:47:14.067 回答
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);
        });
    });
}
于 2018-05-31T10:18:13.473 回答
0

我正在回答我自己的问题以供将来参考。我为使代码正常工作而添加的唯一内容是 Promise。这听起来很容易,但我花了一些时间来掌握这个功能并实现它,但它奏效了,而且值得。非常感谢您的回复。

于 2018-06-03T05:57:03.400 回答