同步使用ImageMagic

时间:2019-05-22 11:28:00

标签: javascript node.js npm imagemagick

尝试使用imagemagick

需要同步使用imagemagick。

即,只有在图像转换完成后才执行下一个代码(无论错误还是成功)

我只看到一种deasync的解决方案:

const ImageMagick = require('imagemagick');
const Deasync = require('deasync');

var finished = false;
ImageMagick.convert(
  [
    source,
    path_to
  ],
  function(err, stdout){
    finished = true;
});

Deasync.loopWhile(function(){return !finished;});

// the next code performed only after image convertion will be done

有什么变种可以与imagemagick同步使用吗?

1 个答案:

答案 0 :(得分:4)

Node.js是单线程的,因此您应尽量避免进行此类同步的功能。您可能只需要在回调函数中执行代码即可。

const ImageMagick = require('imagemagick');

ImageMagick.convert(
  [
    source,
    path_to
  ],
  function(err, stdout){
    // the next code performed only after image convertion will be done
});

或者您可以使用Promise并等待,但是随后您的整个功能将是异步的

const ImageMagic = require('imagemagick');

function convertImage(source, path_to){
    return new Promise((resolve, reject) => {
        ImageMagick.convert(
            [
                source,
                path_to
            ],
            function(err, stdout){
                if(err) {
                    reject(err)
                }
                resolve(stdout);
            });
    })
}

async function doStuff(){
    // start the image convert
    let stdout = await convertImage(source, path_to);
    // now the function will go on when the promise from convert image is resolved
    // the next code performed only after image convertion will be done
}