【问题标题】:Node strange user input async behaviour节点奇怪的用户输入异步行为
【发布时间】:2023-04-07 10:06:01
【问题描述】:

我刚刚习惯了 Node 编程,但是我遇到了这个执行问题,我对此感到有些困惑。

我正在尝试测试写入路径是否已经存在,如果存在则询问用户输入。

function testPath(fileName) {
  fs.exists(path.resolve('.', fileName), function(exists) {
  //the filepath already exists, ask for user confirmation
  if(exists) {
    process.stdin.on('keypress', function (str, key) {
    //print result of keypress to console
    console.log("str: ", str, " key: ", key);

    if ((str.toLowerCase() == "n") || (~["y", "n"].indexOf(str.toLowerCase()))) {
      return false;
    }
    else {
      return true;
    }
  });
  }
  else {
  //the filepath does not already exist - return true
  return true;
}
console.log("Filename in the target directory already exists, would you like to overwrite? (y/n)");
});
}

这个函数作为一个整体将由调用它的 Promise 解决(或不解决)。

发送给用户并等待按键的消息似乎以正确的方式运行,但它会陷入循环并且即使在有效按键时也不会返回,有人知道这是为什么吗?

【问题讨论】:

  • 您的 return truereturn false 在回调内部。它们不返回来自testPath() 的值。我真的无法理解你的问题。也许它是 How do I return the value from an asynchronous function 的副本?
  • 这句话:“这个函数作为一个整体将由调用它的promise来解决(或不解决)。” 完全不清楚。您的代码显示在任何地方都没有使用承诺。此外,promise 不会被“调用”。
  • 我将使用 var = Promise.resolve(testPath())
  • 现在这显然是 How do I return the response from an asynchronous call 的副本。我会关闭它作为重复,但不能因为我投票关闭它不清楚。其他人可以为此关闭它。
  • 你对Promise.resolve(testPath(<fileName>)) 的使用是完全错误的。为此,testPath() 必须自己返回一个 Promise,或者必须同步返回实际值——两者都不做。 Promise 没有知道异步操作何时完成的神奇能力。完成后你必须告诉他们。

标签: javascript node.js promise command-line-interface


【解决方案1】:

如果你想用它作为一个promise,你需要返回一个promise:

function testPath(fileName) {
    return new Promise((resolve, reject) => {
        fs.exists(path.resolve('.', fileName), function(exists) {
        //the filepath already exists, ask for user confirmation
        if(exists) {
            process.stdin.on('keypress', function (str, key) {
            //print result of keypress to console
            console.log("str: ", str, " key: ", key);

            if ((str.toLowerCase() == "n") || (~["y", "n"].indexOf(str.toLowerCase()))) {
            return reject();
            }
            else {
            return resolve();
            }
        });
        }
        else {
        //the filepath does not already exist - return true
        return resolve();
        }
        console.log("Filename in the target directory already exists, would you like to overwrite? (y/n)");
        });
        }
    })

【讨论】:

  • 是的,我相信这就是 OP 所要求的(或至少应该这样做)-如何“承诺”测试-即如何返回最终将解决的承诺响应异步操作fs.exists()导致process.stdin.on('keypress')触发的手动操作的成功路径或其错误路径。
  • 我认为他知道的不够多,不知道这就是他正在寻找的东西。这就是我刚刚粘贴代码的原因。这样他至少知道要寻找承诺
  • 是的,基本上是这样。恕我直言,您发布此答案是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2015-06-09
  • 1970-01-01
  • 2012-08-17
  • 2015-12-29
  • 1970-01-01
相关资源
最近更新 更多