【问题标题】:Use ImageMagic synchronously同步使用 ImageMagic
【发布时间】:2019-05-22 11:28:00
【问题描述】:

尝试使用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 同步工作?

【问题讨论】:

  • node.js的本质是异步的,应该不需要在node.js中同步做事。
  • 你为什么不把你的ImageMagick.convert 调用包装成一个promise 并使用async/await?还是promise.then
  • @TKoL,这是个好主意。谢谢!

标签: javascript node.js npm imagemagick


【解决方案1】:

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 和 await,但是你的整个函数将是异步的

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
}

【讨论】:

  • 我想过,但在我的情况下,无法将下一个代码输入到回调中。
  • 您能否编辑您的问题并提供更多详细信息,为什么您不能这样做,然后可能会找到解决方案。
  • BraveButter,在这里说起来会更容易——我用 Express 将我的项目从 PHP 转移到 Reactjs。我有一个图像(照片)加载器,它创建了许多不同大小的图像。此函数在一个 API 请求中多次一致地调用。所以我认为从previous调用next函数会很麻烦。
  • 为@TKoL 提到的异步等待方法添加了一个代码示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 2017-03-25
  • 2013-01-24
相关资源
最近更新 更多