如何将.then中的值从Node.js模块返回到服务器文件?

问题描述

我正在尝试构建一个模块功能,该功能将调整使用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
});