vivianaranha
vivianaranha

Reputation: 2781

NodeJs Promises - Trying to run async along with wait

I have some Nodejs code and it results

mainFunction();

async function mainFunction(){

    console.log("Start")
    await deleteDSStore(cardsFolder);
    console.log("Done")


}

async function deleteDSStore(folder){
    return new Promise((resolve, reject) => {
        fs.readdir(folder, (err, files) => {
            files.forEach(async(file) => {
                if(file == ".DS_Store"){
                    fs.unlinkSync(folder+file);
                    console.log("Deleted File" + file);
                }
                else if(fs.lstatSync(folder+file).isDirectory()) {
                    await deleteDSStore(folder+file+"/");
                    console.log("was waiting");
                } else {
                    console.log("nothing");
                }
            });
            resolve();
        });
    });
}

Result

Start
Done
was waiting
was waiting

I want to see more like

Start
was waiting
was waiting
Done

Upvotes: 1

Views: 40

Answers (1)

ddor254
ddor254

Reputation: 1628

forEach is an async "runner" meaning that this code will happen eventually but you are not waiting for the forEach to finish its execution.

you can use for of or for in or simply

 await Promise.all(_.map(files, async(file) => {
                if(file == ".DS_Store"){
                    fs.unlinkSync(folder+file);
                    console.log("Deleted File" + file);
                }
                else if(fs.lstatSync(folder+file).isDirectory()) {
                    await deleteDSStore(folder+file+"/");
                    console.log("was waiting");
                } else {
                    console.log("nothing");
                }
            })
)

here _ is loadsh.

Upvotes: 1

Related Questions