0

So I've been wondering if I need to wrap things that take time in a process.nextTick or not.

For example, imagine a function that returns a promise for a xml string translated to an object.

(I've removed require and other trivialities for readability. You know what's going on here.)

// Return a promise for a javascript object
function parseXml(xml) {

    var promise = q.defer();

    var parser = new x2je.Parser(function(result, error) {
        if (!error)
            promise.resolve(result);
        else
            promise.reject(error);
    });

    parser.parseString(xml);

    return promise.promise;
}

You see some people write functions like so:

// Return a promise for a javascript object
function parseXml(xml) {

    var promise = q.defer();

    process.nextTick(function(){
        var parser = new x2je.Parser(function(result, error) {
            if (!error)
                promise.resolve(result);
            else
                promise.reject(error);
        });

        parser.parseString(xml);
    });

    return promise.promise;
}

When do I need to use process.nextTick for best practice coding?

Redsandro
  • 11,060
  • 13
  • 76
  • 106
  • 1
    AFAIK, if the function you're calling is truly async there's no need to use `process.nextTick`. – Alnitak Oct 12 '15 at 17:18
  • So it depends if the function/module implements `process.nextTick`? – Redsandro Oct 12 '15 at 17:27
  • 1
    You hardly ever will need to use it, especially when you already have promise asynchrony guarantees. Let `x2je.Parser` decide what it wants to do (and when). – Bergi Oct 12 '15 at 17:39

1 Answers1

-1

u can get the same thing with setTimeout(function(){//},0); It just places ur function in queue instead of stack ,mostly put to make ur code non-blocking kinda

ref these links for deeper understanding

http://howtonode.org/understanding-process-next-tick

https://www.youtube.com/watch?v=8aGhZQkoFbQ

Aishwat Singh
  • 4,331
  • 2
  • 26
  • 48
  • 2
    the very first link you've quoted says that `process.nextTick` is _far more efficient_ that `setTimeout(_, 0)`, so it's clearly _not_ the same thing. – Alnitak Oct 12 '15 at 17:19