Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Syntax of process.nextTick – arguments passed

I was learning about process.nextTick and playing around with it. Got a small doubt regarding that itself. The first argument of process.nextTick is a callback function, what is the second or third argument?
Consider the following code:
This is printing error on console but not printing "First line" console.log value –

function promise(value, cb) {
    if (typeof value !== 'string') {
        return cb(new TypeError('Value should be string'));
    }
    cb(null, Promise.resolve('Hello'));
}

promise(1, (err, success) => {
    if (err) throw err;
    success.then((res) => console.log(res));
});

console.log('First line');

I tried to correct it using the following code using process.nextTick and it prints "First line" console on the terminal and then the error, which is fine, understandable but I had to pass the callback function and the error to process.nextTick. Is that how it works? Can someone maybe give a better explanation about that? I’m talking about the syntax and number of arguments of process.nextTick here, to be specific –

function promise(value, cb) {
    if (typeof value !== 'string') {
        return process.nextTick(cb,
            new TypeError('Value should be string'));
    }
    cb(null, Promise.resolve('Hello'));
}

promise(1, (err, success) => {
    if (err) throw err;
    success.then((res) => console.log(res));
});

console.log('First line');

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Docs is pretty clear:

process.nextTick(callback[, …args])

  • callback <Function>

  • …args <any> Additional arguments to pass when invoking the callback

That’s how the method works, it takes a callback and optional args to pass to the callback when invoked.

https://nodejs.org/api/process.html#processnexttickcallback-args

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading