Reputation: 3568
I am going through below documentation. https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_use_of_the_completer_function
It is mentioned that the completer function can be called asynchronously if it accepts two arguments:
function completer(linePartial, callback) {
callback(null, [['123'], linePartial]);
}
I am not getting what is 'callback' (I understand callbacks are called, once a function finished execution, but in this cases, where exactly 'callback' function is defined) here? is it separate function that accepts two arguments?
Do I need to define this function named 'callback' explicitly?
Why the first argument of callback is null?
Upvotes: 2
Views: 156
Reputation: 18288
You do not need to write this callback function, it just gets given to you as a parameter to your completer function. Node creates the function internally somewhere.
The way Node has written the callback expects it to be given an error in the first position and the result in the second position. This (err, value) style is very common in Node and other libraries often will use it too.
Here is an example of the completer being used asynchronously (I use a setTimeout to add a 300ms delay between you pressing tab and the results appearing)
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
completer: (line, callback) => {
const completions = '.help .error .exit .quit .q'.split(' ');
const hits = completions.filter((c) => c.startsWith(line));
setTimeout(
() => callback(null, [hits.length ? hits : completions, line]),
300,
);
},
});
rl.question('Press tab to autocomplete\n', (answer) => {
console.log(`you entered: ${answer}! Well done.`);
rl.close();
});
If you want to see the actual code in Node where this completer callback is defined it is here: https://github.com/nodejs/node/blob/master/lib/readline.js#L466
And the place in the code where it checks if you're expecting a callback is here: https://github.com/nodejs/node/blob/master/lib/readline.js#L136
Upvotes: 2