这里有两种方法。但我需要它来完成同步。但它失败了。 我想使用 Promise.all 来保持同步,但我发现图像处理是异步的,并且它无法在循环中拒绝或解析!这确实让我很困惑。 下面是我的代码。我无法捕捉到 res 或错误。它在处理图像后就结束了...甚至不执行测试方法,但我想知道 Promise.all 是同步方法吗?有没有办法捕获 res 或 err 信息?谢谢!
var gm = require('gm')
var fs = require('fs')
var config = require('./imgConfig')
var image = ['1.jpg', '2.jpg', '3.jpg', '4.jpg','5.jpg','6.jpg']
var _image = ['_1.jpg', '_2.jpg', '_3.jpg', '_4.jpg','_5.jpg','6.jpg']
testS()
function testS() {
uploadFiles(image, _image, 'subModule').then(res => {
console.log(res)
}).catch(e => {
console.log(e)
})
}
function uploadFiles(inputArray, outputArray, type) {
return Promise.all([multipleResize(inputArray, outputArray, type), test()])
}
function test() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("object");
resolve("yeah")
}, 100)
})
}
function multipleResize(inputArray, outputArray, type) {
var height = config[type].height;
var width = config[type].width;
return Promise.all(inputArray.map((img, index) => {
return new Promise((resolve, reject) => {
gm(config.inputPath + img)
.resizeExact(width, height)
.noProfile()
.write(config.outputPath + outputArray[index], function (err) {
if (err) {
console.error(err);
return reject(err);
}
try {
fs.unlinkSync(config.inputPath + img); // consider using an async method here as well.
console.log("next" + config.outputPath + outputArray[index]);
console.log('ko');
return resolve();
} catch (e) {
console.error(e);
reject(e);
}
});
});
}));
}
img配置
module.exports = {
'subModule': {
width: 300,
height: 300
},
inputPath:'./input/',
outputPath:'./output/'
}
最佳答案
在multipleResolve
中,您将returnresolve()
作为#forEach()
调用的一部分运行。这可能不是您想要的,因为第一次迭代将解决您返回的 promise ,即使您的所有 gm
.write()
调用都不会完成还没有。
我会考虑做这样的事情 - 请注意 Promise.all()
和 inputArray#map()
的内部使用来转换每个 img
/index
对到它们自己的Promise
。我还交换了一些错误逻辑,以确保尽快检查错误。
function multipleResize(inputArray, outputArray, type) {
var height = config[type].height;
var width = config[type].width;
var flag = 0;
return Promise.all(inputArray.map((img, index) => {
return new Promise((resolve, reject) => {
gm(config.inputPath + img)
.resizeExact(width, height)
.noProfile()
.write(config.outputPath + outputArray[index], function (err) {
if (err) {
console.error(err);
return reject(err);
}
try {
fs.unlinkSync(config.inputPath + img); // consider using an async method here as well.
console.log("next" + config.outputPath + outputArray[index]);
flag++;
console.log('ko');
return resolve();
} catch (e) {
console.error(e);
reject(e);
}
});
});
}));
}
旁注,您似乎(大部分)正确地使用了 Promise,但是当它们通常不同步时,您错误地将它们称为 sync
。
关于javascript - nodejs使用gm模块来处理图像,但我需要它同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799885/