Ale*_*nin 1 javascript imagemagick node.js npm
尝试使用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
Run Code Online (Sandbox Code Playgroud)
是否有任何变体如何同步使用 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
});
Run Code Online (Sandbox Code Playgroud)
或者你可以使用 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
717 次 |
| 最近记录: |