0

I have the following code (logic) in PHP:

$fp = fopen('fp.txt', 'w');
    if ($msg == 'say') {
        fwrite($fp, 'Hello world!');
    }
$msg = 'done';

To convert this into asynchronous event driven code, the author of node for PHP developers suggests I refactor it like this.

$fp = fopen('fp.txt', 'w');
if ($msg == 'say') {
    fwrite($fp, 'Hello world!');
    $msg = 'done';
} else {
    $msg = 'done';
}

And then,

fs.open('fp.txt', 'w', 0666, function(error, fp) {
    if (msg == 'say') {
        fs.write(fp, 'Hello world!', null, 'utf-8', function() {
        msg = 'done';
    });
    } else {
        msg = 'done';
    }
});

You'd clearly see, there is code duplication. 'msg = "done"' is repeated. Can this be avoided? Code duplication is bad practice right?

Is event driven programming always like this?

1 Answer 1

2

Like this:

var done = function() {
    msg = 'done';
};

fs.open('fp.txt', 'w', 0666, function(error, fp) {
    if (msg == 'say') {
        fs.write(fp, 'Hello world!', null, 'utf-8', done);
    } else {
        done();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.