在代码块完成之前承诺正在解决

Promise is resolving before block of code is finished

我正在使用 Jimp 创建图像。在执行下一个代码块之前,我需要等到所有图像都创建完毕。

这是我的脚本和服务器代码:

   //server.js
    var exportImages = () => {
      ImageProcessor.createImage(
        request.body.templatePath,
        request.body.bitPath,
        request.body.exportPath
      ).then((msg) => {
        console.log("In the final then block");
        response.send(msg);
      }).catch((err) => {
        response.send(err.message)
      });
    }

    exportImages();

processor.js

createImage: (templatePath, bitPath, activePath) => {

var jimpBit = new Jimp(bitPath, function(err, img) {
  err ? console.log("error loading bit: " + err) : console.log("Bit loaded");
});

let randomId = Math.floor(Math.random() * 100000) + 1; // # 1-100000
activePath = './active/' + randomId + '/';

return new Promise( (resolve, reject) => {
  fsPromises.readdir(templatePath)
    .then( (templateImages ) => {

      templateImages.forEach( (templateImage, index) => {
        templateImage = './raw/template1/' + templateImage;
        var activeImage = activePath + randomId + '-' + index + '.PNG';

        Jimp.read(templateImage)
          .then( (template) => (template.clone().write(activeImage)))

          .then( () => (Jimp.read(activeImage)))

          .then( (temporaryImage) => {
            temporaryImage
              .composite( jimpBit, 50, 50 )
              .composite( jimpBit, 150, 150 )
              .write(activeImage);
            console.log("Wrote image: " + activeImage);
          })

          .catch( (err) => {
            reject("Error with Jimp: " + err.message);
          });
      });
    })
    .then( () => {
      resolve(activePath);
    })
    .catch( (err) => {
      reject("Error reading files from " + templatePath + "\n" + err.message);
    })
});

有人能帮我理解为什么在创建图像之前调用最后一个 .then 块吗?

我的实际成绩是:

In the final then block
Bit loaded
Created image: ./active/64136/64136-4.PNG
Created image: ./active/64136/64136-2.PNG
Created image: ./active/64136/64136-6.PNG
Created image: ./active/64136/64136-1.PNG
Created image: ./active/64136/64136-7.PNG
Created image: ./active/64136/64136-5.PNG
Created image: ./active/64136/64136-0.PNG
Created image: ./active/64136/64136-3.PNG

首先,永远不会等待 .forEach 中的 Promise

其次,你构造一个新的 Promise,当函数在 Promises 执行器内部调用时 returns 一个 Promise - 这是一个反模式

像下面这样的东西应该适合你

createImage: (templatePath, bitPath, activePath) => {

    var jimpBit = new Jimp(bitPath, (err, img) => err ? console.log("error loading bit: " + err) : console.log("Bit loaded"));

    let randomId = Math.floor(Math.random() * 100000) + 1;
    activePath = './active/' + randomId + '/';

    return fsPromises.readdir(templatePath)
    .then((templateImages) => Promise.all(templateImages.map((templateImage, index) => {
        templateImage = './raw/template1/' + templateImage;
        var activeImage = activePath + randomId + '-' + index + '.PNG';

        return Jimp.read(templateImage)
        .then((template) => (template.clone().write(activeImage)))
        .then(() => (Jimp.read(activeImage)))
        .then((temporaryImage) => temporaryImage
            .composite(jimpBit, 50, 50)
            .composite(jimpBit, 150, 150)
            .writeAsync(activeImage) // *** writeAsync ***
        ).then(() => console.log("Wrote image: " + activeImage))
        .catch((err) => {
            throw "Error with Jimp: " + err.message;
        });
    })))
    .then(() => activePath)
    .catch((err) => {
        throw "Error reading files from " + templatePath + "\n" + err.message;
    });
}