代码之家  ›  专栏  ›  技术社区  ›  Hari Krishna

什么是异步“completer”函数中的回调

  •  1
  • Hari Krishna  · 技术社区  · 6 年前

    我正在浏览下面的文档。 https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_use_of_the_completer_function

    如果completer函数接受两个参数,则可以异步调用它:

    function completer(linePartial, callback) {
      callback(null, [['123'], linePartial]);
    }
    

    我没有得到什么是“回调”(我知道一旦函数完成执行,回调就会被调用,但在这种情况下,确切的“回调”函数定义在哪里)这里?

    是否需要显式定义名为“callback”的函数?

    为什么回调的第一个参数为空?

    1 回复  |  直到 6 年前
        1
  •  1
  •   david    6 年前

    不需要编写这个回调函数,它只是作为completer函数的参数提供给您。Node在内部某处创建函数。

    节点编写回调的方式希望在第一个位置给它一个错误,在第二个位置给它一个结果。这种(err,value)样式在Node中非常常见,其他库也经常使用它。

    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();
    });
    

    https://github.com/nodejs/node/blob/master/lib/readline.js#L466

    代码中检查是否需要回调的位置如下: https://github.com/nodejs/node/blob/master/lib/readline.js#L136