【发布时间】: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 true和return 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