繁体   English   中英

异步计数器 function

[英]Counter in async function

提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文

我是 JS/nodeJS 世界的新手,我对异步思维方式有一些困难......

app.post("/upload", upload.array("files"), uploadFiles);
function uploadFiles(req, res) {
    req.files.forEach(function(file) {
        var linesInserted = 0;
        var linesInError = 0;
        fs.createReadStream(file.destination + file.filename)
        .pipe(parse({ delimiter: ",", columns: false, fromLine: 2 }))
        .on("data", function (row) {
            Model.findOneAndUpdate(
                { code: row[0] },
                { 
                    $set: { 
                        a: row[1],
                        b: row[2],
                        c: row[4],
                        d: row[5],
                        e: row[6],
                        f: moment(row[7], "DD/MM/YYYY").toISOString(),
                        g: moment(row[8], "DD/MM/YYYY").toISOString(),
                        h: row[12].split(/\s/)[0].replace(',','.')
                    },
                    $setOnInsert: { 
                        i: row[0], 
                        j: "airbnb",
                        k: row[3],
                        l: moment(row[10], "DD/MM/YYYY").toISOString()
                    },
                    $push: { 
                        connectedTo: [{ m : "xxx" }, { service: "n", serviceId: "o" }] 
                    }
                },
                { 
                    upsert: true,
                    runValidators: true
                },
                function(err, res) {
                    if (err) {
                        console.log(err);
                        linesInError++;
                    } else if (res) {
                        console.log(linesInserted);
                        linesInserted++;
                    }
                }
            );
        })
        .on("end", function () {
            File.create({
                file: file.destination + file.filename,
                originalName: file.originalname,
                linesInserted: linesInserted,
                linesInError: linesInError
            });

            console.log(`File ${file.originalname} - ${file.destination + file.filename} imported`);
        })
        .on("error", function (error) {
            console.log(error.message);
        });
    });
    res.json({ counterFilesImported: req.files.length });
}

使用此代码,问题在于,最后 File 的值对于 linesInserted 和 linesInError 为 0。 这些计数器在读取文件期间递增,但在“结束”时它们的值为 0。我知道这是异步调用的问题,但我找不到任何解决方案。

我想检索计数器的“真实”值。

感谢您的帮助 !

您的问题是 stream 尽可能快地推送数据/行,完成后它会调用end但它不会在检查 lineCount 之前等待处理行。

我对流的感觉很复杂,但 根据文档,它们是异步可迭代的; 我知道如何合作。

我已将代码更改为 Promises。

app.post("/upload", upload.array("files"), function (req, res) {
  processFiles(req.files);

  res.json({ counterFilesImported: req.files.length });
});

async function processFiles(files) {
  for (const file of files) {
    try { // to catch stream errors

      let linesInserted = 0;
      let linesInError = 0;

      const stream = fs.createReadStream(file.destination + file.filename)
        .pipe(parse({ delimiter: ",", columns: false, fromLine: 2 }));

      for await (const row of stream) {
        try {
          await Model.findOneAndUpdate(
            { code: row[0] },
            {
              $set: {
                a: row[1],
                b: row[2],
                c: row[4],
                d: row[5],
                e: row[6],
                f: moment(row[7], "DD/MM/YYYY").toISOString(),
                g: moment(row[8], "DD/MM/YYYY").toISOString(),
                h: row[12].split(/\s/)[0].replace(',', '.')
              },
              $setOnInsert: {
                i: row[0],
                j: "airbnb",
                k: row[3],
                l: moment(row[10], "DD/MM/YYYY").toISOString()
              },
              $push: {
                connectedTo: [{ m: "xxx" }, { service: "n", serviceId: "o" }]
              }
            },
            {
              upsert: true,
              runValidators: true
            }
          );

          ++linesInserted;

        } catch (err) {

          console.log(err);
          ++linesInError;
        }
      }

      File.create({
        file: file.destination + file.filename,
        originalName: file.originalname,
        linesInserted: linesInserted,
        linesInError: linesInError
      });

      console.log(`File ${file.originalname} - ${file.destination + file.filename} imported`);
    } catch (error) {
      // error with the stream/file
      console.log(error.message);
    }
  }
}
问题未解决?试试搜索: 异步计数器 function
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM