Итак, Джессика, наконец, убедила нас в том, что мы должны еще немного поработать над ее тестом. Она хотела сделать его интерактивным, чтобы люди могли отвечать на вопросы.

Как скажет любой полупорядочный кодер, это просто!

Как скажет любой порядочный кодер, подождите, ей 7 лет, а это Node JS!

Правила, которые я установил для себя, были следующими:

Rule 1 - Don't mention callbacks
Rule 2 - If she gets bored let her go and do something else. 

Каждый раз, когда я выполнял пользовательский ввод в CLI, я использовал великолепный пакет inquirer (https://www.npmjs.com/package/inquirer), даже пишу расширение, когда оно не годилось. то, что я хотел (https://www.npmjs.com/package/inquirer-orderedcheckbox с 12 загрузками!).

На этот раз я использовал простой пакет для чтения (https://www.npmjs.com/package/read). Это позволило нам получить очень простую подсказку.

read({
  prompt: "??"
}, function(err, answer) {
  if (answer == "Prince Philip") {
    console.log("Correct!");
  } else {
    console.log("Wrong");
  }
})

Таким образом, мы задали бы console.log вопрос, а затем запустили read с ‘??’, чтобы запросить ответ. Это даст следующее

1    How many dogs does the Queen have?

?? ANSWER GOES HERE

Однако, чтобы гарантировать, что вопросы не будут заданы одновременно (чертова асинхронность), мы должны гарантировать, что каждый вопрос задается в том же обратном вызове, когда мы обрабатываем ответ, ARGH Помните правило 1. Решением было не говорить о закрывающие фигурные скобки, пока мы не ответили на все вопросы.

Как только нам удалось добавить закрывающие фигурные скобки, мы установили atom-beautify, и Джессика воспользовалась волшебной функцией beautify, чтобы код было легче читать. Окончательный код находится в Git (https://github.com/ChrisPhillips-cminion/JessicasQuiz) и ниже.

Джессика задала вопрос, зачем нам нужен ; в конце каждой строки. Единственная причина, которую я придумал, была «Чтобы Джек не стонала на меня», но она, похоже, приняла это.

**Мы не обещаем, что ответы на вопросы будут правильными!**

var sleep = require('sleep').sleep
var color = require('colors');
var read = require('read');
j = 1
totalAnswers = 0
console.log("Queen quiz - by Jessica".bold)
sleep(2)
read({
  prompt: "What is your name?"
}, function(err, answer) {
  console.log("Hello " + answer)
  console.log("")
  console.log(j++ + "\tHow many dogs does the Queen have?".yellow)
  console.log("")
  read({
    prompt: "??"
  }, function(err, answer) {
    if (answer == "30") {
      console.log("Correct!");
    } else {
      console.log("Wrong");
    }
    console.log(j++ + "\tHow many grandchildren does the Queen have?");
    console.log("")
    read({
      prompt: "??"
    }, function(err, answer) {
      if (answer == "8") {
        console.log("Correct!");
      } else {
        console.log("Wrong");
      }
      console.log(j++ + "\tHow many castles does the Queen have?".magenta);
      console.log("")
      read({
        prompt: "??"
      }, function(err, answer) {
        if (answer == "8") {
          console.log("Correct!");
        } else {
          console.log("Wrong");
        }
console.log(j++ + "\tHow many princesses does the Queen have?".blue);
        console.log("")
        read({
          prompt: "??"
        }, function(err, answer) {
          if (answer == "4") {
            console.log("Correct!");
          } else {
            console.log("Wrong");
          }
console.log(j++ + "\tHow many types of dogs does the Queen have?".green);
          console.log("")
          read({
            prompt: "??"
          }, function(err, answer) {
            if (answer == "6") {
              console.log("Correct!");
            } else {
              console.log("Wrong");
            }
console.log(j++ + "\tHow many princes deos the Queen have?".cyan);
            console.log("")
            read({
              prompt: "??"
            }, function(err, answer) {
              if (answer == "5") {
                console.log("Correct!");
              } else {
                console.log("Wrong");
              }
console.log(j++ + "\tWho is the Queen's Great Great Grandmother?".magenta);
              console.log("")
              read({
                prompt: "??"
              }, function(err, answer) {
                if (answer == "Victoria") {
                  console.log("Correct!");
                } else {
                  console.log("Wrong");
                }
                console.log(j++ + "\tWho is the Queen's Great Grandmother?");
                console.log("")
                read({
                  prompt: "??"
                }, function(err, answer) {
                  if (answer == "Alexandra") {
                    console.log("Correct!");
                  } else {
                    console.log("Wrong");
                  }
                  console.log(j++ + "\tHow old is the Queen?".rainbow.bold);
                  console.log("")
                  read({
                    prompt: "??"
                  }, function(err, answer) {
                    if (answer == "91") {
                      console.log("Correct!");
                    } else {
                      console.log("Wrong");
                    }
                    console.log(j++ + "\thow old was the Queen when she became Queen?".magenta);
                    console.log("")
                    read({
                      prompt: "??"
                    }, function(err, answer) {
                      if (answer == "25") {
                        console.log("Correct!");
                      } else {
                        console.log("Wrong");
                      }
                      console.log(j++ + "\tHow many countries does the Queen rule?".rainbow.bold);
                      console.log("")
                      read({
                        prompt: "??"
                      }, function(err, answer) {
                        if (answer == "16") {
                          console.log("Correct!");
                        } else {
                          console.log("Wrong");
                        }
                        console.log("")
console.log(j++ + "\tHow many sister does the Queen have?".magenta);
read({
                          prompt: "??"
                        }, function(err, answer) {
                          if (answer == "1") {
                            console.log("Correct!");
                          } else {
                            console.log("Wrong");
                          }
                          console.log(j++ + "\tWho is the Duke of Edinburgh?".magenta);
                          console.log("")
                          read({
                            prompt: "??"
                          }, function(err, answer) {
                            if (answer == "Prince Philip") {
                              console.log("Correct!");
                            } else {
                              console.log("Wrong");
                            }
                            console.log(j++ + "\tHow old was the Queen in May 1926?".magenta);
                            console.log("")
                            read({
                              prompt: "??"
                            }, function(err, answer) {
                              if (answer == "0") {
                                console.log("Correct!");
                              } else {
                                console.log("Wrong");
                              }
                              console.log(j++ + "\tDid George VI like to knit?".magenta);
                              console.log("")
                              read({
                                prompt: "??"
                              }, function(err, answer) {
                                if (answer == "yes") {
                                  console.log("Correct!");
                                } else {
                                  console.log("Wrong");
                                }
                                console.log(j++ + "\tWho did the Queen marry?".magenta);
                                console.log("")
                                read({
                                  prompt: "??"
                                }, function(err, answer) {
                                  if (answer == "Prince Philip") {
                                    console.log("Correct!");
                                  } else {
                                    console.log("Wrong");
                                  }
                                })
                              })
                            })
                          })
                        })
                      })
                    })
                  })
                })
              })
            })
          })
        })
      })
    })
  })
})

Так что осталось

  1. Проверка вопросов
  2. Функции
  3. Улучшенная практика обратного вызова
  4. Документирование кода на ходу!