【问题标题】:How to handle multiple arrays in asynchronous methods in node.js如何在node.js中的异步方法中处理多个数组
【发布时间】:2018-11-10 00:27:29
【问题描述】:

我有一个非常大的数组(10K),我想拆分它(我按照这个做了:https://stackoverflow.com/a/8495740/2183053 并且它有效)但我需要将 tempArray 传递给 request 并等待将传递给的响应保存到数据库。

谁能帮帮我。为了清楚起见,我想拆分大数组并将分离的数组传递给请求函数,然后传递给保存到 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);
    }
  })
}

【问题讨论】:

    标签: javascript arrays node.js asynchronous


    【解决方案1】:

    你需要 promise 来处理 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);
    };
    

    【讨论】:

    • 嗨,谢谢你的回答。但是在这个过程中,promise 有什么帮助呢?
    • 承诺工作,直到一个服务完成,下一个服务等待第一个服务结果将等待。它同步工作
    • 好的。让我试着学习一下如何在我的代码中实现它的承诺。希望它有效。太感谢了。我是节点的新手,那是你不知道承诺。大声笑
    • 当我刚接触 nodejs 时,我不知道 promise 我只是停留在异步之间。我所有的代码都在这里和那里毁了。所以你不是新的。不断从错误中学习。
    【解决方案2】:

    我添加了一些承诺。

    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);
            });
        });
    }
    

    【讨论】:

    • 嗨,谢谢你的回答。我尝试运行此代码,但它说“等待仅在异步函数中有效”。我用谷歌搜索,似乎还没有解决方案。大声笑。
    • 嘿,我发现了如何处理这个问题。太感谢了。但是 arrayWillReturn 不返回切片数组,但它返回整个 10K 数组。知道为什么吗?
    【解决方案3】:

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

    【讨论】:

    • 您好,我已经在您的代码中添加了承诺,比那个答案早一个月。
    猜你喜欢
    • 2023-03-06
    • 2019-05-12
    • 2017-02-26
    • 1970-01-01
    • 2019-03-21
    • 2017-09-19
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多