我很抱歉问一个已经发布了多次的问题,但我不明白如何将示例/解决方案/教程适应我的代码。我受到修改别人的代码的约束,无法从头开始。
我正在使用nodejs v6.10,尽管阅读了许多文章和Wiki,但我很难实施异步代码处理。
。我试图确切确定所有操作何时完成,我相信承诺对我来说是正确的方法。我不知道如何使其正常工作,但是我再也不会收到任何警告或错误了。
我认为我最大的问题是我的图像操纵功能不会返回任何东西,我试图强迫他们而没有成功。
这是我的基本代码:
var finished;
main();
function main() {
do stuff...
fs.readFile(JSON,...) {
finished = theApp(JSON);
});
Promise.all(finished).then(function(x, y) {
var total = x * y;
console.log("completed: " + total + " at " + Date.now());
}).catch(function() {
console.log("failed.");
});
}
function theApp(JSON) {
do stuff...
for $loop (1..100) {
do JSON stuff...
resizeImages(JSONparameters, image);
}
for $loop2 (1..100) {
do JSON stuff...
finished = function() {
return manipulateImages(JSONparameters, image);
}
}
}
function resizeImages(JSONparameters, image) {
do stuff...
for $i (1..100) {
sharp(image)
.resize(x, y)
.toFile(output)
}
}
function manipulateImages(JSONparameters, image) {
return new Promise(function(resolve, reject) {
do stuff...
for $i (1..100) {
sharp(image)
.blur()
.toFile(output)
}
});
}
我意识到这是很多循环,但这是我目前的限制。我也意识到我只在操纵图中放下诺言。这是因为调整大小操作在操作开始之前完成。
在此配置中,ManiPulationImages函数被称为多次,但没有输出。如果我围绕代码剥离"返回新承诺"包装,则可以正常工作。但是后来我不知道如何返回可以将任何可以传递给主的东西等待等待直到promises.all((返回解决方案。
有人可以教育我如何允许我安慰。谢谢。
我认为您对诺言的基本理解不完全存在,您的解决方案已经足够复杂,以至于您更难理解承诺的核心以及它们的工作方式。这样考虑:
// List of images
let images = [
'image1.jpg',
'image2.jpg',
'image3.jpg',
]
// Array to store promises
let promises = []
// Loop through your images
for (const image of images) {
// Create a new promise, adding it to the array
promises.push(new Promise((resolve, reject) => {
// Do your resizing, manipulation, etc
sharp(image)
.resize()
.blur()
.toFile(output, function(err, data) { // Assuming this toFile is an async operation and uses a callback
// After all the resizing, manipulation and file saving async functions are complete, resolve the Promise
resolve()
})
})
}
// Wait until all promises in the promises array are resolved
Promise.all(promises)
.then((){
console.log('image resizing and manipulation is complete')
})
理解诺言的最佳方法是,在您的诺言中,您可以做所有异步工作。处理回调等。完成后,resolve
。这就是信号表明承诺已经完成。
Promise.all
正在等待承诺数组中的所有承诺在运行之前完成的 .then()
方法。