سؤال

I am relatively new to javascript and working on nodejs. I have a situation if reduced woulf boil down to following code. Can I return directly in the callback with out creating another variable(temp) like I did in the below code.

exports.run = function(req, res) {

    var testRunId = req.body.testRunId;
    var testFileDir = './uploads/temptestfiles/'+ testRunId + '/';

    var error = null
    var status ;

    mkpath(testFileDir, function (err) {

        if (!err) {
            error = {error:'could not create logs directory'}
            status = 500
        };

    });

    if (status === 500) {
        return res.send(500, error);
    }

//handle many more cases

}

Following is dumbed down version.

var a = function(param,callback) {
    callback(param);
};

var base = function() {
    val temp = null;        
    a(5, function(a){
        //can I do something like return 2*a and end the parent function
        temp = 2*a;
    });

    return temp;
}

I realised I actually needed to use sync version of mkpath as I dont want to run further code before that dir is created. so changed my code to

try {
    mkpath.sync(testFileDir);
} catch(err) {
    return res.status(500).send({error:'couldn\'t create directory to store log files'});
}
هل كانت مفيدة؟

المحلول

On you dumbed down question (which is synchronous). Sure you could, but you'd have to return the value from your callback, your callback handler and your calling function.

var a = function (param, callback) {
  return callback(param);
};

var base = function () {
  return a(5, function (a) {
      return 2*a;
    });
}

This would not work in an asynchronous case, Then you need callback functions, or instead returning a deferred, promise or future.

For example

function asynchDoubler(number) {
  var deferred = new Deferred();
  setTimeout(function () {
      deferred.callback(2*number);
    }, 1);
  return deferred;
}

asynchDoubler(5).addCallback(function (result) { 
    console.log(result); 
  });
// outputs 10
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top