Home > database >  Syntax of process.nextTick - arguments passed
Syntax of process.nextTick - arguments passed

Time:05-02

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');

CodePudding user response:

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

  • Related