Promise resolve fires before task is complete

时间:2017-08-14 07:08:11

标签: node.js promise restify

I'm using a promise function and Jimp to resize an image, save it in a folder, and then return the path to the new resized image.

However, the resolve() function in resizeWidth() is fired before image.resize().write() is done, which means my app crashes because it cannot find the new file.

Any help would be greatly appreciated.

const fs = require('fs');
const path = require('path');
const jimp = require('jimp');

const resizeWidth = function(file, width) {
  return new Promise((resolve, reject) => {
    jimp.read(path.join(__dirname, '..', 'assets', 'images', file), (err, image) => {
      if (err) reject(err);
      const xSize = parseInt(width);
      image.resize(xSize, jimp.AUTO)
        .write(path.join(__dirname, '..', 'assets', 'images', 'tmp', file));
      resolve(path.join(__dirname, '..', 'assets', 'images', 'tmp', file));
    });
  });
};

module.exports = function(server) {
  server.get('/images/:name/:width', (req, res) => {
    resizeWidth(req.params.name, req.params.width)
      .then(() => {
        fs.readFile(path.join(__dirname, '..', 'assets', 'images', 'tmp', req.params.name),
          (err, newData) => {
            if (err) throw err;
            res.sendRaw(200, newData, {
              'Content-Length': Buffer.byteLength(newData)
            });
            res.end();
          });
      })
      .catch((err) => {
        console.log(err);
      });
  });
};

1 个答案:

答案 0 :(得分:2)

write是异步函数,因此在写入函数完成之前调用resolve。使用回调来确保订单

jimp.read(path.join(__dirname, '..', 'assets', 'images', file), (err, image) => {
  if (err) reject(err);
  const xSize = parseInt(width);
  image.resize(xSize, jimp.AUTO)
    .write(path.join(__dirname, '..', 'assets', 'images', 'tmp', file), () => {
       resolve(path.join(__dirname, '..', 'assets', 'images', 'tmp', file));
    });
});
相关问题