Beginner question about async function inside another function

50 views
Skip to first unread message

António Ramos

unread,
Sep 11, 2012, 9:29:49 AM9/11/12
to nod...@googlegroups.com
What i want is to create a function to read files and return the files to the caller.

This code is not working!


my func in coffeescript 


fs = require('fs')


InitLoadTasks =->
  a=[]
  fs.readdir __dirname+ '/toRun', (err, files) ->
    if (err) 
      console.log(err)
    a=files
initLoadTasks()


reads files from directory

how do i return the a array as a return value to InitLoadTasks?





Mark Volkmann

unread,
Sep 11, 2012, 10:27:36 AM9/11/12
to nod...@googlegroups.com
The initLoadTasks function does something asynchronous, so you need to pass it a callback function that will be invoked when it finishes.
If the only thing you want is a list of the files in a given directory, you don't need to write initLoadTasks. You can just call fs.readdir.
However, supposing you want to do something more, here's how you could write it in JavaScript.

var fs = require('fs');

function initLoadTasks(subDir, cb) {
  fs.readDir(__dirname + '/' + subDir, function (err, files) {
    if (err) {
      return cb(err);
    }
    // do extra processing here
    cb(null, files);
  });
}

initLoadTasks('toRun', function (err, files) {
  // do something with files here after checking err
});
 
--
R. Mark Volkmann
Object Computing, Inc.

Elliot

unread,
Sep 11, 2012, 10:56:34 AM9/11/12
to nod...@googlegroups.com

If you're only doing it on startup, you could also use the synchronous version of readdir.

On Sep 11, 2012 7:27 AM, "Mark Volkmann" <r.mark....@gmail.com> wrote:

António Ramos

unread,
Sep 13, 2012, 4:58:05 AM9/13/12
to nod...@googlegroups.com
got it
 
why is the first parameter of the callback null in
cb(null, files);
?
 
thank you
António

2012/9/11 Elliot <efo...@firetaco.com>

If you're only doing it on startup, you could also use the synchronous version of readdir.

On Sep 11, 2012 7:27 AM, "Mark Volkmann" <r.mark....@gmail.com> wrote:

--
Job Board: http://jobs.nodejs.org/
Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com
To unsubscribe from this group, send email to
nodejs+un...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Mark Volkmann

unread,
Sep 13, 2012, 6:34:26 AM9/13/12
to nod...@googlegroups.com
Convention is for the first argument to callbacks to be an error description. If there was no error, null is passed.

---
R. Mark Volkmann
Object Computing, Inc.
Reply all
Reply to author
Forward
0 new messages