简体   繁体   English

在所有承诺得到解决后执行承诺

[英]Execute promise after all promises were resolved

I've written some code that iterates through a directory, picks all the jpg files, rename them, create thumbs folder and put them inside that folder. 我编写了一些迭代目录的代码,选择所有的jpg文件,重命名它们,创建thumb文件夹并将它们放在该文件夹中。 I have also coded a function that generates a chunk of html per image, and at the end of the forEach loop should write all the output into a file. 我还编写了一个函数,每个图像生成一个html块,并且在forEach循环结束时应该将所有输出写入文件。

// Read the directory
fs.readdir(dir, function (err, files) {

// Return the error if something went wrong
if (err) {
    console.log("Something went wrong");
}

//Make thumbs dir
fs.mkdirSync(thumbsFolder);

// For every file in the list
files.forEach(function (file) {
    var extension = path.extname(file);

    if (extension === ".jpg") {

        //Rename images
        var renameTask = renameImages(file, newFileName, extension);

        //Generating thumbs
        renameTask.then(function (newFileName) {
            generateThumbs(dir, newFileName, thumbsFolder)
            console.log("Promise resolved! Generating thumb for: " + newFileName);
            galleryHtml += generateThumbsGallery(newFileName, articleTitle);

        }, function (err) {
            console.log(err);
        });

    }

});

//Gallery output
console.log("Gallery Output: ");
console.log(galleryHtml);

}); });

My problem is that as logic as it sounds, galleryHtml (that is already defined in the upper part of the code, and not included here), returns undefined, because it runs before all the previous promises were resolved. 我的问题是,听起来像逻辑一样,galleryHtml(已在代码的上半部分定义,此处未包含)返回undefined,因为它在所有先前的promise都被解析之前运行。

I've read about Promise.all method, and that I should pass a promises array, the question is that I don´t know how many promises would be returned, and in my code "renameTask" is the variable that acts as the promise receiver. 我已经阅读了Promise.all方法,并且我应该传递一个promises数组,问题是我不知道会返回多少个promise,而在我的代码中“renameTask”是作为promise的变量接收器。

So, I would need some help -That I really appreciate in advance- to understand how to put the forEach as a promise itself, and after all forEach promises were resolved, then execute a final promise. 所以,我需要一些帮助 - 我真的很感激 - 要了解如何将forEach作为一个承诺本身,并且毕竟每个承诺都得到解决,然后执行最后的承诺。

Thanks so much in advance. 非常感谢提前。

UPDATE: 更新:

Felix, thanks so much, I'm closer now 菲利克斯,非常感谢,我现在离我很近了

// Read the directory
fs.readdir(dir, function (err, files) {

    // Return the error if something went wrong
    if (err) {
        console.log("Something went wrong");
    }

    var promises = [];

    //Make thumbs dir
    fs.mkdirSync(thumbsFolder);

    // For every file in the list
    files.forEach(function (file) {
        var extension = path.extname(file);

        if (extension === ".jpg") {

            //Rename images
            var renameTask = renameImages(file, newFileName, extension);


            promises.push(renameTask.then(function (newFileName) {
                    generateThumbs(dir, newFileName, thumbsFolder)
                    console.log("Promise resolved! Generating thumb for: " + newFileName);
                    galleryHtml += generateThumbsGallery(newFileName, articleTitle);
                }, function (err) {
                    console.log(err);
                }) 
            );

            console.log("<<<< Promises length: " + promises.length + " >>>>");

        }

    });

    Promise.all(promises).then(function () {
        console.log("<<<<< All promises were resolved >>>>");
    });

});

The thing is that I'm never getting the message "<<<<< All promises were resolved >>>>", I know that it should be a little thing that I'm missing.. Thanks again for your help! 问题是,我永远不会收到消息“<<<<<所有承诺都得到解决>>>>”,我知道这应该是我失踪的一件小事......再次感谢您的帮助!

I've read about Promise.all method, and that I should pass a promises array, the question is that I don´t know how many promises would be returned, and in my code "renameTask" is the variable that acts as the promise receiver. 我已经阅读了Promise.all方法,并且我应该传递一个promises数组,问题是我不知道会返回多少个promise,而在我的代码中“renameTask”是作为promise的变量接收器。

It's not as complicated as you seem to think. 它并不像你想象的那么复杂。 Create an array, add the promises to it and pass the array to Promise.all : 创建一个数组,将promises添加到它并将数组传递给Promise.all

var promises = []; // array of promises

files.forEach(function (file) {
    var extension = path.extname(file);
    if (extension === ".jpg") {
        var renameTask = renameImages(file, newFileName, extension);
        promises.push(renameTask.then(...)); // add promise
    }

});

Promise.all(promises).then(...); // use array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM