Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

javascript - When do I need to use process.nextTick in node.js for best practice async functions?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...