gpt4 book ai didi

javascript - "While"阻塞异步操作

转载 作者:搜寻专家 更新时间:2023-11-01 00:49:48 25 4
gpt4 key购买 nike

当我尝试运行该代码时 -

const MagicHomeControl = require("magic-home").Control;
const readlineSync = require("readline-sync");

const light = new MagicHomeControl("192.168.1.77");

let answer;

while(true){
answer = readlineSync.question("What do you wish to do?\nTurn on - on\nTurn off - off\nQuit the program - quit\n");
switch(answer){
case "on":
light.turnOn(function(err, success){

});
break;
case "off":
light.turnOff(function(err, success){

});
break;
case "quit":
process.exit(-1);
break;
default:
console.log("Wrong input, try again");
break;
}
}

只有退出选项才能正常工作。但是,如果我编写相同的代码,但没有 while 循环 = 一切正常,但只有一次。有什么想法吗?

最佳答案

在调用turnOnturnOff 后,您会立即调用readlineSync.question,这可能会阻止turnOn 背后的API 的任何可能性turnOff 函数来完成,或者至少向 JavaScript 报告。

您可以通过使循环异步来解决这个问题,并且仅在 turnOnturnOff 操作完成时才“迭代”:

(function loop(err, success) {
if (err) console.log(err);
const answer = readlineSync.question("What do you wish to do?\nTurn on - on\nTurn off - off\nQuit the program - quit\n");
switch(answer){
case "on":
light.turnOn(loop);
break;
case "off":
light.turnOff(loop);
break;
case "quit":
process.exit(-1);
break;
default:
console.log("Wrong input, try again");
setTimeout(loop); // Also do this asynchronously to save the stack.
}
})(); // IIFE - immediately invoked function expression

关于javascript - "While"阻塞异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com