0

Just having some issues with building a function using nodeJS. It doesn't seem to be returning the value, and I have a feeling its due to the asynchronous nature of the function call. Any help would be really appreciated!

sendFilesToDB is sent an array (from fs.readdir) of files to be processed. The files' content is used to construct a SQL query. Once successfully inserted, the file is deleted. But the fileToQuery function does not return a string at all (gives a 'Argument must be a string' error).

1 Answer 1

4

fileToQuery is returning void, because it says:

function fileToQuery(filePath) { do_something(...); } 

That return statement you have isn't returning from filesToQuery but from the anonymous function you defined it in.

You need to rewrite your fileToQuery function to take an extra argument (perhaps resultCallback) and instead of returning your sql string, you do:

return resultCallback("INSERT IGNORE ...."); 

You'll then call it like this:

fileToQuery(file,function(query){ client.query(query, function(err, results) { fs.unlink(file, function(err) { sendFilesToDB(files); }); }); }); 

By the way: This is called "continuation passing style" and can be done in any language that supports anonymous functions. What you asked for is called a callable continuation, but not very many languages have them. If you're interested in learning about them you should try picking up scheme.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, I was wanting to avoid that, but I guess thats the way its done. I come from a PHP background, where a function execute, and return before continuing on. It just seems unnatural how things are nested like the above. Thanks!
The function did return. It just didn't return what you think it did, and when. As a matter of fact, PHP supports continuations (and thus continuation passing style) as well, so you can write this way in PHP.
Ah, that would make sense. Thanks for your answer! Although my code needs tweaking further now, as it no longer seems to monitor continuously...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.