如何实时显示Javascript输出?

时间:2019-03-06 03:37:32

标签: javascript

很抱歉,如果这是一个简单的问题,但是有一种方法可以将Javascript实时输出到控制台,同时暂停每次用户交互。换句话说,如果我做的事情很简单...

console.log("What's your name: ");
let userName = prompt("What is your name?");
console.log(userName);

console.log("\n");

console.log("Nice to meet you " + userName + "! What is your age?");
let userAge = prompt("What is your age?");
console.log(userAge);

...我可以在年龄提示出现之前将名称输出到屏幕吗?这在其他教学环境(MS Basic和命令提示符)中是可行的,但是要么Javascript中不存在,要么我遗漏了一些东西。

感谢帮助新手!

2 个答案:

答案 0 :(得分:1)

您可以使用setTimeout,如下所示:

console.log("What's your name: ");
let userName = prompt("What is your name?");
console.log(userName);

console.log("\n");
setTimeout(function(){
console.log("Nice to meet you " + userName + "! What is your age?");
let userAge = prompt("What is your age?");
console.log(userAge);
},1000)

注意:这是一种实现方法,还有许多其他方法可以实现。

如果您要使用诺言:

let userName,userAge, userSport;
function basic(){
console.log("What's your name: ");
var promise1 = new Promise(function(resolve, reject){
userName = prompt("What is your name?");
resolve(userName)
})
promise1.then(function(value){
console.log(value);
console.log("\n");
console.log("Nice to meet you " + value + "! What is your age?");
var promise2 =  new Promise(function(resolve, reject){
userAge = prompt("What is your age?");
resolve(userAge)
})
promise2.then(function(value){
console.log(value)
console.log("Nice to meet you " + userName + " aged: " +userAge + ". Let us know your favorite sports")

var promise3 = new Promise(function(resolve, reject){
userSport = prompt("What is your favorite sports?");
resolve(userSport)
})
promise3.then(function(value){
console.log(value)
console.log("Nice to meet you " + userName + " aged:  " +userAge + " and your favorite sports is " +value)
console.log("\n");
console.log("Thanks");
})
})
})

}
basic()

答案 1 :(得分:1)

您可以使用async/await功能和承诺。我个人并不总是喜欢使用.then,所以这是我使用Promises的版本。

const Q1 = () => new Promise(resolve => {
  let userName = prompt('What is your name?');
  console.log(`What is your name: ${userName}`);
  resolve(userName);
})

const Q2 = (userName) => new Promise(resolve => {
  console.log(`Nice to meet you ${userName}! What is your age?`);
  let age = prompt('What is your age?');
  console.log(age);
  resolve(age);
})

 const userPrompt = async () => {
   let name = await Q1();
   let age = await Q2(name); // assigned to variable should you want to use it in next question
 }
 
 userPrompt();

您现在可以将其他问题添加为函数。

这也是指向JSFiddle的链接。如果运行它并打开控制台,则会看到在打开年龄提示之前显示了该名称。