[英]How to avoid jimp blocking the code node.js
我正在用Jimp操縱一些照片。
我有一個帶照片的數組。 像這樣:
var images = ['.../pic-1.jpg', '.../pic-2.jpg', '.../pic-3.jpg', '.../pic-4.jpg'];
這是操縱它們的代碼:
images.forEach(function(image){
jimp.read(image, function(err, img){
img.quality(90, function(){
console.log("done with this image!");
});
});
});
這在每個圖像完成時記錄得很好。 但是,它阻止了代碼,如果我嘗試這個:
var processed = 0;
images.forEach(function(image){
jimp.read(image, function(err, img){
img.quality(90, function(){
processed++;
document.querySelector('p').textContent = 'processed images: ' + processed;
});
});
});
在處理完所有圖像之前,它不會更新文本。 我該如何解決這個問題,以便每次處理圖像時都可以更新文本?
它可能看起來像這樣,因為所有內容都是並行發生而不是按順序發生,或者實際上大部分時間都花在了img.quality()
並且它是一個阻塞主線程的CPU密集型任務。
您可以嘗試更改此內容:
images.forEach(function(image){
jimp.read(image, function(err, img){
img.quality(90, function(){
processed++;
document.querySelector('p').textContent = 'processed images: ' + processed;
});
});
});
這樣的事情:
let processed = 0;
let f = () => {
jimp.read(images[processed], function(err, img){
img.quality(90, function(){
processed++;
document.querySelector('p').textContent = 'processed images: ' + processed;
if (processed < images.length) setImmediate(f);
});
});
};
您還可以更改setImmediate
到setTimout
一些超時值,將讓UI線程它需要繪制在屏幕上繪制。 你甚至可以使用window.requestAnimationFrame()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.