首页 > 解决方案 > Jimp.read never runs callback and hangs up

问题描述

I'm trying to make a Discord bot, and one of my commands resizes a requested image and sends it. When I run the command though, it just hangs up with no error message. If I take out the callback and run it normally, it sends, but sends the last image requested instead of the one that just was.

function resizeImg(id,_callback) {
            const img = Jimp.read('image.png')
                .then(img => {
                    return img
                        .resize(100,130)
                        .write('temp.png');
                    _callback();
                })
            .catch(console.error);
}

resizeImg(id,function() {
            var attachment = new Discord.MessageAttachment('./temp.png')
            msg.channel.send('',attachment)
});

标签: javascriptnode.js

解决方案


return由于停止执行的语句,您永远不会达到回调。

function resizeImg(id, _callback) {
  Jimp.read('image.png').then(img => {
    const img = img.resize(100,130).write('temp.png');
    _callback(img);
  })
  .catch(console.error);
}

resizeImg(id, function(img) {
  var attachment = new Discord.MessageAttachment('./temp.png')
  msg.channel.send('', attachment)
});

试试上面的代码。您现在可以通过回调中的参数访问 img。


推荐阅读