Does something like this work in asynchronous code?

regular = 'a string';
enriched = enrichString(regular);
sys.puts(enriched);

function enrichString(str){
    //run str through some regex stuff or other string manipulations
    return str;
}

Now it seems that I am doing what I hoped it would do, but I do not know if it is safe. Could this lead to undefined sometimes? 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!

+3
source share
3 answers

You only need callbacks if you are making asynchronous non-blocking calls.

var string = "foo",
    new_string = enrich(foo);

doStuff(new_string);

Safe if enrichblocked. for instance

function enrich(str) {
    // do regex stuff with str

    // manipulate it

    return str;
}

blocks, so it's safe to do it. Where

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:

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);
    });

note that

enriched = enrichString(regular, sys.puts(data));

It does not work because you pass the return value sys.puts(data)as your parameter to the function (data is undefined too!)

You need to pass a function.

+2

, . . , , -— -, , ..

+3

Just to add a Pointy answer, people sometimes call asynchronous behavior with process.nextTick (or in the browser setTimeout (fn, 0)) - this causes the current execution context to give. Example: https://github.com/caolan/async/blob/master/lib/async.js#L408-410

0
source

All Articles