简体   繁体   中英

Promise is resolving before block of code is finished

I'm using Jimp to create images. I need to wait until all of the images are created before executing the next block of code.

Here is my script and server code:

   //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);
    })
});

Could someone help me understand why the last .then block is getting called before the images are created?

My actual results are:

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

Firstly, the Promises inside.forEach are never waited for

Secondly, you construct a new Promise, when the function called inside the Promises executor returns a Promise - this is an anti-pattern

Something like the following should work for you

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;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM