0

上传 csv 文件并且数据库中已存在数字时,我无法向前端发送错误。后端正在记录主键值已存在的错误,但我编写的代码告诉前端文件上传正常。

代码片段:

router.post('/:program/upload', upload.single('testUpload'), (req, res, next) => {
  try {
    CSVtoPSQL(req.params.program, req.file.filename)
    return res.status(201).json({
      message: 'File Uploaded Just fine :)'
    });
  } catch (error) {
    return res.status(500).json({
      message: error
    })
  }
});

const CSVtoPSQL = (program, filePath) => {
  let stream = fs.createReadStream(path.resolve(__dirname, '../files', filePath));
  let csvData = [];
  let csvStream = csv
    .parse({ headers: false })
    .on('error', error => console.error(error))
    .on('data', (data) => {
      csvData.push(data.toString());
    })
    .on('end', () => {
      csvData.forEach(item => {
        queries.upload(program, item)
          .then(() => {
            console.log('QR Code Added: ' + item);
          }).catch((err) => {
            console.log(`oopsie: ${err}`);
          });
      })
    });
  stream.pipe(csvStream);
}

非常有信心问题在于我对承诺的理解不足。

4

1 回答 1

1

正如所料,我没有正确处理我的承诺。我已经稍微更新了代码,现在它以 2 组成功上传和错误上传来响应。

router.post('/:program/upload', upload.single('testUpload'), async (req, res, next) => {
  try {
    const result = await CSVtoPSQL(req.params.program, req.file.filename)
    return res.status(201).json(result);
  }
  catch (error) {
    return res.status(500).json({
      message: error,
    })
  }
});

const CSVtoPSQL = (program, filePath) => {
  let stream = fs.createReadStream(path.resolve(__dirname, '../files', filePath));
  let csvData = [];

  return new Promise((resolve) => {
    const results = {
      seccess: [],
      error: [],
    }

    let csvStream = csv
      .parse({ headers: false })
      .on('error', error => console.error(error))
      .on('data', (data) => {
        csvData.push(data.toString());
      })
      .on('end', async () => {
        await Promise.all(
          csvData.map(async (item) => {
            try{
              await queries.upload(program, item);
              results.success.push(item);
              console.log('QR Code Added: ' + item);
            }
            catch (error) {
              console.log(`oopsie: ${error}`)
              results.error.push(item);
            }
          })
        )
        resolve(results);
      });
    stream.pipe(csvStream);
  })
}
于 2021-01-26T17:35:22.657 回答