简体   繁体   中英

Promise with two for loops nested Javascript

I would like to create an asynchronous method with promise but I can't understand why it doesn't worked with my program below :

app.get('/historique', function (req, res) {

  const pathFolders = `.\\..\\website\\src\\assets\\covering\\`;

  const promise2 = new Promise(function (resolve, reject) {

    fs.readdirSync(pathFolders).forEach(folder => {

      recursive(`${pathFolders}\\${folder}\\`, function (err, files) {

        var datapath = [];

        files.forEach(file => {

          console.log("1");

        });

        console.log("2");
      });

      console.log("3");
      resolve("3");
    });

  });

  promise2.then(function (value) {
    console.log("end")
    res.status(200).send("end")
  });

})

Normally, I would like the program to show in the order on the console.log 1 1 1 2 1 1 2 ... then 3 and finally "end". But the console.log show me first 3 then "end" then 1 1 1 2 1 1 2 ...

Can you help me please. I think this is because of the for loop but I can't solve this problem.

As E. Zacarias already explained in his comment, the recursive-readdir implementation is implemented asynchronously. But it supports being used with a Promise by leaving out the callback argument.

Then you can return a Promise from the iterator function and wait for it with Promise.all .

This will make your code much more straightforward:

app.get('/historique', function (req, res) {

  const pathFolders = `.\\..\\website\\src\\assets\\covering\\`;

  const promise2 = Promise.all(
    // readdirSync returns an Array of folder name strings
    // Call Array.map to transform it into an array of Promise
    fs.readdirSync(pathFolders).map(folder => {
      // return a Promise for the folder from the map function
      return recursive(`${pathFolders}\\${folder}\\`).then(files => {
        var datapath = [];
        files.forEach(file => {
          console.log("1");
        });
        console.log("2");
      });
    });
  );

  promise2.then( value => {
    console.log("end")
    res.status(200).send("end")
  });

})

The important aspects here are to understand the workings of Array.prototype.map and Promise.all .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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