Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...