regular = 'a string';
enriched = enrichString(regular);
sys.puts(enriched);
function enrichString(str){
//run str through some regex stuff or other string manipulations
return str;
}
Right now it seems to be doing what I hoped it would do but I don't know if its safe. Could this result in undefined sometimes? Do I need to do something like:
regular = 'a string';
enriched = enrichString(regular, function(data){sys.puts(data);});
function enrichString(str, cb){
//run str through some regex stuff or other string manipulations
cb(str);
}
Thanks for the help!
No, you should be fine. Straight runs of computational code are inherently not asynchronous. Callbacks are needed when there's some action involving external resources — file I/O, network operations, some operating system interactions, etc.
You only need callbacks if your making asychronous non-blocking calls.
var string = "foo",
new_string = enrich(foo);
doStuff(new_string);
Is safe if enrich is blocking. For example
function enrich(str) {
// do regex stuff with str
// manipulate it
return str;
}
is blocking so it's safe to do this. Where as
function enrich(str) {
// get some data from the database.
// store the string in a file.
return str;
}
Uses non blocking IO and is not safe. What you want to do is this :
function enrich(str, cb) {
// get some data from the database.
// store the string in a file.
return cb(str);
}
var string = "foo",
new_string = enrich(foo, function (str) {
doStuff(new_string);
});
Notice that
enriched = enrichString(regular, sys.puts(data));
Does not work because your passing in the return value of sys.puts(data) as your function parameter (data is undefined aswell!)
You need to pass in a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With