同步使用 ImageMagic
Use ImageMagic synchronously
尝试使用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 是单线程的,所以你应该尽量避免使函数像这样同步。您可能只需在回调函数中执行代码即可。
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
}
尝试使用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 是单线程的,所以你应该尽量避免使函数像这样同步。您可能只需在回调函数中执行代码即可。
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
}