“同时”阻止异步操作

时间:2018-12-08 16:15:30

标签: javascript node.js

当我尝试运行该代码时-

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循环=一切工作正常,但只有一次。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

调用turnOnturnOff后,您立即调用readlineSync.question,这可能会阻止turnOnturnOff函数后面的API完成的所有可能性,或至少要向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