读取nodejs中的Promise of Promise属性

问题描述 投票:0回答:1

基本上,我要实现的是在中间件中检查上传的文件是否具有正确的图像类型(例如png)。这是我到目前为止提出的:

export const fileCheckMiddleware = (req, res, next) => {
  const acceptedImageTypes = ["image/gif", "image/jpeg", "image/png"];

  const oldWrite = res.write;
  const oldEnd = res.end;

  const chunks = [];

  res.write = (...restArgs) => {
  chunks.push(new Buffer(restArgs[0]));
  oldWrite.apply(res, restArgs);
 };

  res.end = async (...restArgs) => {
if (restArgs[0]) {
  chunks.push(new Buffer(restArgs[0]));
}

const body = Buffer.concat(chunks).toString("utf8");

try {
  let parsedBody = {};
  try {
    parsedBody = JSON.parse(body);
  } catch (err) {
    parsedBody = { data: { unparsedBody: body } };
  }

  const { variables } = req.body;

  console.log("\x1b[1m%s\x1b[0m", "LOG variables", variables.file);
  if (variables.file) {
    console.log("\x1b[1m%s\x1b[0m", "LOG type", typeof variables.file);
  }
} catch (err) {}
oldEnd.apply(res, restArgs);
   };
  next();
};

记录的变量类型。文件是一个对象。 console.log的结果是这样的:

LOG variables Promise {
 { filename: 'trump.jpeg',
   mimetype: 'image/jpeg',
   encoding: '7bit',
   createReadStream: [Function: createReadStream] } }

所以我如何在这里访问模仿类型?我试图映射键,variables.file [“ Promise”],...

javascript node.js promise filestream
1个回答
0
投票

Promise不是variables.file的键,它是variables.file的类型。这意味着您的代码将在HTTP请求启动后立即开始执行,并且文件是异步接收的,因此您必须执行以下操作:

variables.file.then(file => {
    // Do whatever you want with the file
    next();
});

或将周围的function声明为async,然后执行此操作:

const file = await variables.file;
// Do whatever you want with the file
next();
© www.soinside.com 2019 - 2024. All rights reserved.