0

I am confused with one behavior of async and await. I have a promise.all with a map calling another async function. inside that async function I have a file writing fs.writeFile() feature that has a callback. I want to do something once all the promise.all promises are resolved. But, fs.writefile() callback is always completing late. i.e. the console written after promise.all is getting printed first and then zip completion console.

here is the code:

ingite = async () => {
    let users = await storage.getData('users');

    let result = await Promise.all(
        users.map( async user =>{
            await datagenerator.fetchAllData(user.user);
        })
    );
    if(result) {

        console.log("All Done -->");
    }
}

function that was called

fetchAllData = async  (userName) => {



    await fs.writeFile(`${global.appRoot}/user_data/${userName}/test.html`, template, function(err) {
        if (err) {
        console.log(err);
        } else {
            zipFolder(`${global.appRoot}/user_data/${userName}`, `${global.appRoot}/user_zip/${userName}-info.zip`, function(err) {
            if(err) {

            } else {
                const file = `${global.appRoot}/user_zip/info.zip`;
                console.log('ZIP generated successfully for -->'  , userName);
            }
            });
        }
    });

Here, in the code 'ZIP generated successfully for -->' for some users comes after

console.log("All Done -->");

Can anyone suggest me what is going wrong?

vaibhav
  • 762
  • 2
  • 12
  • 34
  • `writeFile` is callback-based, not Promise-based. Promisify it instead, so that it returns a Promise and can be used with `.then` instead of a callback. You need to do the same with `zipFolder` – CertainPerformance Nov 11 '19 at 09:34
  • Use `const fs = require('fs').promises;` instead of just `const fs = require('fs');` – Titus Nov 11 '19 at 09:35
  • If you need this to be sync you can use `writeFileSync` intead of `writeFile`. See the details [here](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) – Sonu Bamniya Nov 11 '19 at 10:45

0 Answers0