【发布时间】:2016-08-16 10:37:01
【问题描述】:
这里有两种方法。但我需要它来完成同步。但它失败了。 我想使用 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);
}
});
});
}));
}
imgConfig
module.exports = {
'subModule': {
width: 300,
height: 300
},
inputPath:'./input/',
outputPath:'./output/'
}
【问题讨论】:
标签: javascript node.js