How to use callback or Async in for loop?











up vote
0
down vote

favorite












I search and read about Asynchronous functions and callbacks. But i was not able to solve my problem for a week. I want to do 'fs readfile' inside loop with order. I try the following but i am not successful.



// on the code below, console.log print the value in random order and 'storedata' is empity.
// my goal is to do readfile in loop orderly and store the value

router.get("/files/readfiles", function(req,res){
var storedata= ;
var filenames= ["file1","file2","file3","file4"];

for (var i=0; i< filenames.length; i++){
fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
if (err) throw err;
storedata.push(data);
console.log(data);
});
console.log(storedata); // this returns empty array
});


I also try in another way:



router.get("/files/readfiles", function(req,res){
var filenames= ["file1","file2","file3","file4"];

filenames.forEach(readfiles);

function readfiles(value) {
var dataread = fs.readFile('views/allfiles/'+ value +'.ejs','utf8')

console.log (dataread);
}
});


on the above try i get an error of: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function.



I am new to Asynchronous methods any help please.










share|improve this question
























  • Possible duplicate of How do I return the response from an asynchronous call?
    – Jared Smith
    Nov 20 at 16:39






  • 2




    You will have to either use the sync version or Promise.all. Either way you will need to understand what asynchronous means, of course console.log(storedata) logs an empty array as the IO hasn't completed yet when it runs. If you use a callback you only have access to the data in a callback.
    – Jared Smith
    Nov 20 at 16:39












  • What exactly is the result you want? Blast through it as fast as possible, or read one file at a time.
    – Kevin B
    Nov 20 at 16:42










  • @Kevin i want to do fs read file inside loop (read multiple file orderly) then store the value to use it . this is what i want as i wrote in the question.
    – wzwd
    Nov 20 at 16:45










  • @wzwd Yes, i understand that, but due to the asynchronous nature of reading files, you have two different ways of doing it. You haven't specified which one would be preferred.
    – Kevin B
    Nov 20 at 16:49

















up vote
0
down vote

favorite












I search and read about Asynchronous functions and callbacks. But i was not able to solve my problem for a week. I want to do 'fs readfile' inside loop with order. I try the following but i am not successful.



// on the code below, console.log print the value in random order and 'storedata' is empity.
// my goal is to do readfile in loop orderly and store the value

router.get("/files/readfiles", function(req,res){
var storedata= ;
var filenames= ["file1","file2","file3","file4"];

for (var i=0; i< filenames.length; i++){
fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
if (err) throw err;
storedata.push(data);
console.log(data);
});
console.log(storedata); // this returns empty array
});


I also try in another way:



router.get("/files/readfiles", function(req,res){
var filenames= ["file1","file2","file3","file4"];

filenames.forEach(readfiles);

function readfiles(value) {
var dataread = fs.readFile('views/allfiles/'+ value +'.ejs','utf8')

console.log (dataread);
}
});


on the above try i get an error of: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function.



I am new to Asynchronous methods any help please.










share|improve this question
























  • Possible duplicate of How do I return the response from an asynchronous call?
    – Jared Smith
    Nov 20 at 16:39






  • 2




    You will have to either use the sync version or Promise.all. Either way you will need to understand what asynchronous means, of course console.log(storedata) logs an empty array as the IO hasn't completed yet when it runs. If you use a callback you only have access to the data in a callback.
    – Jared Smith
    Nov 20 at 16:39












  • What exactly is the result you want? Blast through it as fast as possible, or read one file at a time.
    – Kevin B
    Nov 20 at 16:42










  • @Kevin i want to do fs read file inside loop (read multiple file orderly) then store the value to use it . this is what i want as i wrote in the question.
    – wzwd
    Nov 20 at 16:45










  • @wzwd Yes, i understand that, but due to the asynchronous nature of reading files, you have two different ways of doing it. You haven't specified which one would be preferred.
    – Kevin B
    Nov 20 at 16:49















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I search and read about Asynchronous functions and callbacks. But i was not able to solve my problem for a week. I want to do 'fs readfile' inside loop with order. I try the following but i am not successful.



// on the code below, console.log print the value in random order and 'storedata' is empity.
// my goal is to do readfile in loop orderly and store the value

router.get("/files/readfiles", function(req,res){
var storedata= ;
var filenames= ["file1","file2","file3","file4"];

for (var i=0; i< filenames.length; i++){
fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
if (err) throw err;
storedata.push(data);
console.log(data);
});
console.log(storedata); // this returns empty array
});


I also try in another way:



router.get("/files/readfiles", function(req,res){
var filenames= ["file1","file2","file3","file4"];

filenames.forEach(readfiles);

function readfiles(value) {
var dataread = fs.readFile('views/allfiles/'+ value +'.ejs','utf8')

console.log (dataread);
}
});


on the above try i get an error of: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function.



I am new to Asynchronous methods any help please.










share|improve this question















I search and read about Asynchronous functions and callbacks. But i was not able to solve my problem for a week. I want to do 'fs readfile' inside loop with order. I try the following but i am not successful.



// on the code below, console.log print the value in random order and 'storedata' is empity.
// my goal is to do readfile in loop orderly and store the value

router.get("/files/readfiles", function(req,res){
var storedata= ;
var filenames= ["file1","file2","file3","file4"];

for (var i=0; i< filenames.length; i++){
fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
if (err) throw err;
storedata.push(data);
console.log(data);
});
console.log(storedata); // this returns empty array
});


I also try in another way:



router.get("/files/readfiles", function(req,res){
var filenames= ["file1","file2","file3","file4"];

filenames.forEach(readfiles);

function readfiles(value) {
var dataread = fs.readFile('views/allfiles/'+ value +'.ejs','utf8')

console.log (dataread);
}
});


on the above try i get an error of: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function.



I am new to Asynchronous methods any help please.







javascript node.js asynchronous






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 17:40









iagowp

1,069824




1,069824










asked Nov 20 at 16:37









wzwd

296




296












  • Possible duplicate of How do I return the response from an asynchronous call?
    – Jared Smith
    Nov 20 at 16:39






  • 2




    You will have to either use the sync version or Promise.all. Either way you will need to understand what asynchronous means, of course console.log(storedata) logs an empty array as the IO hasn't completed yet when it runs. If you use a callback you only have access to the data in a callback.
    – Jared Smith
    Nov 20 at 16:39












  • What exactly is the result you want? Blast through it as fast as possible, or read one file at a time.
    – Kevin B
    Nov 20 at 16:42










  • @Kevin i want to do fs read file inside loop (read multiple file orderly) then store the value to use it . this is what i want as i wrote in the question.
    – wzwd
    Nov 20 at 16:45










  • @wzwd Yes, i understand that, but due to the asynchronous nature of reading files, you have two different ways of doing it. You haven't specified which one would be preferred.
    – Kevin B
    Nov 20 at 16:49




















  • Possible duplicate of How do I return the response from an asynchronous call?
    – Jared Smith
    Nov 20 at 16:39






  • 2




    You will have to either use the sync version or Promise.all. Either way you will need to understand what asynchronous means, of course console.log(storedata) logs an empty array as the IO hasn't completed yet when it runs. If you use a callback you only have access to the data in a callback.
    – Jared Smith
    Nov 20 at 16:39












  • What exactly is the result you want? Blast through it as fast as possible, or read one file at a time.
    – Kevin B
    Nov 20 at 16:42










  • @Kevin i want to do fs read file inside loop (read multiple file orderly) then store the value to use it . this is what i want as i wrote in the question.
    – wzwd
    Nov 20 at 16:45










  • @wzwd Yes, i understand that, but due to the asynchronous nature of reading files, you have two different ways of doing it. You haven't specified which one would be preferred.
    – Kevin B
    Nov 20 at 16:49


















Possible duplicate of How do I return the response from an asynchronous call?
– Jared Smith
Nov 20 at 16:39




Possible duplicate of How do I return the response from an asynchronous call?
– Jared Smith
Nov 20 at 16:39




2




2




You will have to either use the sync version or Promise.all. Either way you will need to understand what asynchronous means, of course console.log(storedata) logs an empty array as the IO hasn't completed yet when it runs. If you use a callback you only have access to the data in a callback.
– Jared Smith
Nov 20 at 16:39






You will have to either use the sync version or Promise.all. Either way you will need to understand what asynchronous means, of course console.log(storedata) logs an empty array as the IO hasn't completed yet when it runs. If you use a callback you only have access to the data in a callback.
– Jared Smith
Nov 20 at 16:39














What exactly is the result you want? Blast through it as fast as possible, or read one file at a time.
– Kevin B
Nov 20 at 16:42




What exactly is the result you want? Blast through it as fast as possible, or read one file at a time.
– Kevin B
Nov 20 at 16:42












@Kevin i want to do fs read file inside loop (read multiple file orderly) then store the value to use it . this is what i want as i wrote in the question.
– wzwd
Nov 20 at 16:45




@Kevin i want to do fs read file inside loop (read multiple file orderly) then store the value to use it . this is what i want as i wrote in the question.
– wzwd
Nov 20 at 16:45












@wzwd Yes, i understand that, but due to the asynchronous nature of reading files, you have two different ways of doing it. You haven't specified which one would be preferred.
– Kevin B
Nov 20 at 16:49






@wzwd Yes, i understand that, but due to the asynchronous nature of reading files, you have two different ways of doing it. You haven't specified which one would be preferred.
– Kevin B
Nov 20 at 16:49














3 Answers
3






active

oldest

votes

















up vote
0
down vote



accepted










If you're using Node v10 or above you can use the fs promises API and async/await.



To read the files in series:



router.get( "/files/readfiles", async function( req, res ) {
const storedata = [ ];
const filenames = [ "file1", "file2" , "file3", "file4" ];

for (let i = 0; i < filenames.length; i++ ) {
const data = await fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
storedata.push( data );
}

console.log( storedata );

} );


or to read them in parallel:



router.get( "/files/readfiles", async function( req, res ) {
const promises = [ ];
const filenames = [ "file1", "file2", "file3", "file4" ];

for (let i = 0; i < filenames.length; i++ ) {
const promise = fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
promises.push( promise );
}

const storedata = await Promise.all( promises );

console.log( storedata );

} );





share|improve this answer





















  • On the 1st method i get: 'parsing error: Unexpected token fs'. I can't modify this line. On the second method i get a result of:` [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> },]` (node:3575) ExperimentalWarning: The fs.promises API is experimental
    – wzwd
    Nov 20 at 17:21










  • @wzwd Sounds like you didn't put the async keyword in front of function.
    – Paulpro
    Nov 20 at 19:24










  • The ExperimentalWarning should be there, but it's just printed to stderr and shouldn't affect your program.
    – Paulpro
    Nov 20 at 19:28










  • Yes i forgot to add Async on the function. It perfectly works. Thanks
    – wzwd
    Nov 21 at 10:52


















up vote
0
down vote













You should use ES2017 async/await syntax like this.



router.get("/files/readfiles", async function(req, res){
var storedata= ;
var filenames= ["file1","file2","file3","file4"];

for (var i=0; i< filenames.length; i++){
await new Promise((resolve, reject) => {
fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
if (err) return reject( err )
storedata.push(data);
resolve();
});
})
console.log(storedata);
}
});





share|improve this answer




























    up vote
    -1
    down vote













    Your second code doesnt provide a callback function, thats your error.



    Your first code, you are trying to work with callbacks, so you'll need to follow your code nested into the callback, thats what is called callback hell



    It would look like this:



    router.get("/files/readfiles", function(req,res){
    var storedata= ;
    var filenames= ["file1","file2","file3","file4"];

    for (let i = 0; i< filenames.length; i++){
    fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
    if (err) throw err;
    storedata[i] = data;

    if (storedata.length === filenames.length) {
    console.log(storedata);
    // do stuff you want, like:
    res.send(storedata)
    }
    });
    });


    If you plan on using node 10, I recommend you look at the other answer with Promise.all. Async/await is great






    share|improve this answer























    • Thanks it is working, I need to read more about callback , Async/await, promise. I am using Node v10.6.0 but i have no idea this time how to use Promise and Async. may be if you have some links to study i will follow it
      – wzwd
      Nov 20 at 17:29











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53397538%2fhow-to-use-callback-or-async-in-for-loop%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    If you're using Node v10 or above you can use the fs promises API and async/await.



    To read the files in series:



    router.get( "/files/readfiles", async function( req, res ) {
    const storedata = [ ];
    const filenames = [ "file1", "file2" , "file3", "file4" ];

    for (let i = 0; i < filenames.length; i++ ) {
    const data = await fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
    storedata.push( data );
    }

    console.log( storedata );

    } );


    or to read them in parallel:



    router.get( "/files/readfiles", async function( req, res ) {
    const promises = [ ];
    const filenames = [ "file1", "file2", "file3", "file4" ];

    for (let i = 0; i < filenames.length; i++ ) {
    const promise = fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
    promises.push( promise );
    }

    const storedata = await Promise.all( promises );

    console.log( storedata );

    } );





    share|improve this answer





















    • On the 1st method i get: 'parsing error: Unexpected token fs'. I can't modify this line. On the second method i get a result of:` [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> },]` (node:3575) ExperimentalWarning: The fs.promises API is experimental
      – wzwd
      Nov 20 at 17:21










    • @wzwd Sounds like you didn't put the async keyword in front of function.
      – Paulpro
      Nov 20 at 19:24










    • The ExperimentalWarning should be there, but it's just printed to stderr and shouldn't affect your program.
      – Paulpro
      Nov 20 at 19:28










    • Yes i forgot to add Async on the function. It perfectly works. Thanks
      – wzwd
      Nov 21 at 10:52















    up vote
    0
    down vote



    accepted










    If you're using Node v10 or above you can use the fs promises API and async/await.



    To read the files in series:



    router.get( "/files/readfiles", async function( req, res ) {
    const storedata = [ ];
    const filenames = [ "file1", "file2" , "file3", "file4" ];

    for (let i = 0; i < filenames.length; i++ ) {
    const data = await fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
    storedata.push( data );
    }

    console.log( storedata );

    } );


    or to read them in parallel:



    router.get( "/files/readfiles", async function( req, res ) {
    const promises = [ ];
    const filenames = [ "file1", "file2", "file3", "file4" ];

    for (let i = 0; i < filenames.length; i++ ) {
    const promise = fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
    promises.push( promise );
    }

    const storedata = await Promise.all( promises );

    console.log( storedata );

    } );





    share|improve this answer





















    • On the 1st method i get: 'parsing error: Unexpected token fs'. I can't modify this line. On the second method i get a result of:` [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> },]` (node:3575) ExperimentalWarning: The fs.promises API is experimental
      – wzwd
      Nov 20 at 17:21










    • @wzwd Sounds like you didn't put the async keyword in front of function.
      – Paulpro
      Nov 20 at 19:24










    • The ExperimentalWarning should be there, but it's just printed to stderr and shouldn't affect your program.
      – Paulpro
      Nov 20 at 19:28










    • Yes i forgot to add Async on the function. It perfectly works. Thanks
      – wzwd
      Nov 21 at 10:52













    up vote
    0
    down vote



    accepted







    up vote
    0
    down vote



    accepted






    If you're using Node v10 or above you can use the fs promises API and async/await.



    To read the files in series:



    router.get( "/files/readfiles", async function( req, res ) {
    const storedata = [ ];
    const filenames = [ "file1", "file2" , "file3", "file4" ];

    for (let i = 0; i < filenames.length; i++ ) {
    const data = await fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
    storedata.push( data );
    }

    console.log( storedata );

    } );


    or to read them in parallel:



    router.get( "/files/readfiles", async function( req, res ) {
    const promises = [ ];
    const filenames = [ "file1", "file2", "file3", "file4" ];

    for (let i = 0; i < filenames.length; i++ ) {
    const promise = fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
    promises.push( promise );
    }

    const storedata = await Promise.all( promises );

    console.log( storedata );

    } );





    share|improve this answer












    If you're using Node v10 or above you can use the fs promises API and async/await.



    To read the files in series:



    router.get( "/files/readfiles", async function( req, res ) {
    const storedata = [ ];
    const filenames = [ "file1", "file2" , "file3", "file4" ];

    for (let i = 0; i < filenames.length; i++ ) {
    const data = await fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
    storedata.push( data );
    }

    console.log( storedata );

    } );


    or to read them in parallel:



    router.get( "/files/readfiles", async function( req, res ) {
    const promises = [ ];
    const filenames = [ "file1", "file2", "file3", "file4" ];

    for (let i = 0; i < filenames.length; i++ ) {
    const promise = fs.promises.readFile( 'views/allfiles/'+ filenames[i] +'.ejs', { encoding: 'utf8' } );
    promises.push( promise );
    }

    const storedata = await Promise.all( promises );

    console.log( storedata );

    } );






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 20 at 16:44









    Paulpro

    112k15222230




    112k15222230












    • On the 1st method i get: 'parsing error: Unexpected token fs'. I can't modify this line. On the second method i get a result of:` [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> },]` (node:3575) ExperimentalWarning: The fs.promises API is experimental
      – wzwd
      Nov 20 at 17:21










    • @wzwd Sounds like you didn't put the async keyword in front of function.
      – Paulpro
      Nov 20 at 19:24










    • The ExperimentalWarning should be there, but it's just printed to stderr and shouldn't affect your program.
      – Paulpro
      Nov 20 at 19:28










    • Yes i forgot to add Async on the function. It perfectly works. Thanks
      – wzwd
      Nov 21 at 10:52


















    • On the 1st method i get: 'parsing error: Unexpected token fs'. I can't modify this line. On the second method i get a result of:` [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> },]` (node:3575) ExperimentalWarning: The fs.promises API is experimental
      – wzwd
      Nov 20 at 17:21










    • @wzwd Sounds like you didn't put the async keyword in front of function.
      – Paulpro
      Nov 20 at 19:24










    • The ExperimentalWarning should be there, but it's just printed to stderr and shouldn't affect your program.
      – Paulpro
      Nov 20 at 19:28










    • Yes i forgot to add Async on the function. It perfectly works. Thanks
      – wzwd
      Nov 21 at 10:52
















    On the 1st method i get: 'parsing error: Unexpected token fs'. I can't modify this line. On the second method i get a result of:` [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> },]` (node:3575) ExperimentalWarning: The fs.promises API is experimental
    – wzwd
    Nov 20 at 17:21




    On the 1st method i get: 'parsing error: Unexpected token fs'. I can't modify this line. On the second method i get a result of:` [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> }, Promise { <pending> },]` (node:3575) ExperimentalWarning: The fs.promises API is experimental
    – wzwd
    Nov 20 at 17:21












    @wzwd Sounds like you didn't put the async keyword in front of function.
    – Paulpro
    Nov 20 at 19:24




    @wzwd Sounds like you didn't put the async keyword in front of function.
    – Paulpro
    Nov 20 at 19:24












    The ExperimentalWarning should be there, but it's just printed to stderr and shouldn't affect your program.
    – Paulpro
    Nov 20 at 19:28




    The ExperimentalWarning should be there, but it's just printed to stderr and shouldn't affect your program.
    – Paulpro
    Nov 20 at 19:28












    Yes i forgot to add Async on the function. It perfectly works. Thanks
    – wzwd
    Nov 21 at 10:52




    Yes i forgot to add Async on the function. It perfectly works. Thanks
    – wzwd
    Nov 21 at 10:52












    up vote
    0
    down vote













    You should use ES2017 async/await syntax like this.



    router.get("/files/readfiles", async function(req, res){
    var storedata= ;
    var filenames= ["file1","file2","file3","file4"];

    for (var i=0; i< filenames.length; i++){
    await new Promise((resolve, reject) => {
    fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
    if (err) return reject( err )
    storedata.push(data);
    resolve();
    });
    })
    console.log(storedata);
    }
    });





    share|improve this answer

























      up vote
      0
      down vote













      You should use ES2017 async/await syntax like this.



      router.get("/files/readfiles", async function(req, res){
      var storedata= ;
      var filenames= ["file1","file2","file3","file4"];

      for (var i=0; i< filenames.length; i++){
      await new Promise((resolve, reject) => {
      fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
      if (err) return reject( err )
      storedata.push(data);
      resolve();
      });
      })
      console.log(storedata);
      }
      });





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        You should use ES2017 async/await syntax like this.



        router.get("/files/readfiles", async function(req, res){
        var storedata= ;
        var filenames= ["file1","file2","file3","file4"];

        for (var i=0; i< filenames.length; i++){
        await new Promise((resolve, reject) => {
        fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
        if (err) return reject( err )
        storedata.push(data);
        resolve();
        });
        })
        console.log(storedata);
        }
        });





        share|improve this answer












        You should use ES2017 async/await syntax like this.



        router.get("/files/readfiles", async function(req, res){
        var storedata= ;
        var filenames= ["file1","file2","file3","file4"];

        for (var i=0; i< filenames.length; i++){
        await new Promise((resolve, reject) => {
        fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
        if (err) return reject( err )
        storedata.push(data);
        resolve();
        });
        })
        console.log(storedata);
        }
        });






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 6 at 19:24









        Fernando Carvajal

        599513




        599513






















            up vote
            -1
            down vote













            Your second code doesnt provide a callback function, thats your error.



            Your first code, you are trying to work with callbacks, so you'll need to follow your code nested into the callback, thats what is called callback hell



            It would look like this:



            router.get("/files/readfiles", function(req,res){
            var storedata= ;
            var filenames= ["file1","file2","file3","file4"];

            for (let i = 0; i< filenames.length; i++){
            fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
            if (err) throw err;
            storedata[i] = data;

            if (storedata.length === filenames.length) {
            console.log(storedata);
            // do stuff you want, like:
            res.send(storedata)
            }
            });
            });


            If you plan on using node 10, I recommend you look at the other answer with Promise.all. Async/await is great






            share|improve this answer























            • Thanks it is working, I need to read more about callback , Async/await, promise. I am using Node v10.6.0 but i have no idea this time how to use Promise and Async. may be if you have some links to study i will follow it
              – wzwd
              Nov 20 at 17:29















            up vote
            -1
            down vote













            Your second code doesnt provide a callback function, thats your error.



            Your first code, you are trying to work with callbacks, so you'll need to follow your code nested into the callback, thats what is called callback hell



            It would look like this:



            router.get("/files/readfiles", function(req,res){
            var storedata= ;
            var filenames= ["file1","file2","file3","file4"];

            for (let i = 0; i< filenames.length; i++){
            fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
            if (err) throw err;
            storedata[i] = data;

            if (storedata.length === filenames.length) {
            console.log(storedata);
            // do stuff you want, like:
            res.send(storedata)
            }
            });
            });


            If you plan on using node 10, I recommend you look at the other answer with Promise.all. Async/await is great






            share|improve this answer























            • Thanks it is working, I need to read more about callback , Async/await, promise. I am using Node v10.6.0 but i have no idea this time how to use Promise and Async. may be if you have some links to study i will follow it
              – wzwd
              Nov 20 at 17:29













            up vote
            -1
            down vote










            up vote
            -1
            down vote









            Your second code doesnt provide a callback function, thats your error.



            Your first code, you are trying to work with callbacks, so you'll need to follow your code nested into the callback, thats what is called callback hell



            It would look like this:



            router.get("/files/readfiles", function(req,res){
            var storedata= ;
            var filenames= ["file1","file2","file3","file4"];

            for (let i = 0; i< filenames.length; i++){
            fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
            if (err) throw err;
            storedata[i] = data;

            if (storedata.length === filenames.length) {
            console.log(storedata);
            // do stuff you want, like:
            res.send(storedata)
            }
            });
            });


            If you plan on using node 10, I recommend you look at the other answer with Promise.all. Async/await is great






            share|improve this answer














            Your second code doesnt provide a callback function, thats your error.



            Your first code, you are trying to work with callbacks, so you'll need to follow your code nested into the callback, thats what is called callback hell



            It would look like this:



            router.get("/files/readfiles", function(req,res){
            var storedata= ;
            var filenames= ["file1","file2","file3","file4"];

            for (let i = 0; i< filenames.length; i++){
            fs.readFile('views/allfiles/'+ filenames[i] +'.ejs','utf8',function (err, data) {
            if (err) throw err;
            storedata[i] = data;

            if (storedata.length === filenames.length) {
            console.log(storedata);
            // do stuff you want, like:
            res.send(storedata)
            }
            });
            });


            If you plan on using node 10, I recommend you look at the other answer with Promise.all. Async/await is great







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 20 at 17:27

























            answered Nov 20 at 16:56









            iagowp

            1,069824




            1,069824












            • Thanks it is working, I need to read more about callback , Async/await, promise. I am using Node v10.6.0 but i have no idea this time how to use Promise and Async. may be if you have some links to study i will follow it
              – wzwd
              Nov 20 at 17:29


















            • Thanks it is working, I need to read more about callback , Async/await, promise. I am using Node v10.6.0 but i have no idea this time how to use Promise and Async. may be if you have some links to study i will follow it
              – wzwd
              Nov 20 at 17:29
















            Thanks it is working, I need to read more about callback , Async/await, promise. I am using Node v10.6.0 but i have no idea this time how to use Promise and Async. may be if you have some links to study i will follow it
            – wzwd
            Nov 20 at 17:29




            Thanks it is working, I need to read more about callback , Async/await, promise. I am using Node v10.6.0 but i have no idea this time how to use Promise and Async. may be if you have some links to study i will follow it
            – wzwd
            Nov 20 at 17:29


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53397538%2fhow-to-use-callback-or-async-in-for-loop%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            Refactoring coordinates for Minecraft Pi buildings written in Python