如何 return .then() 中的值从 Node.js 模块到服务器文件?

How to return a value inside the .then() from Node.js module to server file?

我正在尝试构建一个模块函数,该函数将使用 Sharp 调整传递给它的图像的大小。 我将图像数据完美地记录在下面给出的 .then() 中,但是当我 return 同样的结果时,结果却是 undefined.

请帮我找出我做错了什么。

模块

exports.scaleImg = function (w,h,givenPath){
          let toInsertImgData;
          sharp(givenPath)
            .resize(w, h)
            .jpeg({
              quality: 80,
              chromaSubsampling: "4:4:4",
            })
            .toFile(compressedImgPath)
            .then(() => {
              fsPromises.readFile(compressedImgPath).then((imgData) => {
                  toInsertImgData = {
                    data: imgData,
                    contentType: "image/jpeg",
                  };
                  console.log(toInsertImgData);
                  return(toInsertImgData);
              });
            });
            
      }

这里compressedImgPath只是根目录下一个文件夹的路径

服务器文件

const imageScalingModule = require(__dirname+"/modules.js");



app.post("/compose",upload.fields([{ name: "propic" }, { name: "image" }]),
      (req, res) => {

           console.log(imageScalingModule.scaleImg(640, 480, req.files.image[0].path));
});

then() returns a promise,因此您需要更改 /compose-处理程序中的代码以等待承诺解决(我正在使用 async/await,但你也可以 scaleImg(...).then()):

app.post("/compose",upload.fields([{ name: "propic" }, { name: "image" }]),
      async (req, res) => {
          const res = await imageScalingModule.scaleImg(640, 480, req.files.image[0].path);
          console.log(res);
          res.send(res); // you probably want to do something like this, otherwise the request hangs
});