Node.js:多个然后没有按正确的顺序执行(Node.js: Multiple then's not executing in the correct order)

编程入门 行业动态 更新时间:2024-10-27 16:33:48
Node.js:多个然后没有按正确的顺序执行(Node.js: Multiple then's not executing in the correct order)

我是NodeJS的新手,我正在尝试使用promises来提示用户输入特定的顺序。 这是我的代码:

var prompt = require('prompt'); var promising = require("promise-adapter"); var promptGet = promising(prompt.get); prompt.start(); function Game () { playerOneName = ''; playerTwoName = ''; pOneType = true; } //prompts the user for two names and assigns them //to player one and player to for the game object Game.prototype.getName = function (resolve){ promptGet(['playerName1', 'playerName2']).then(function(result){ this.playerOneName = result.playerName1; this.playerTwoName = result.playerName2; }) .then(function() { resolve(); }); } Game.prototype.getType = function (resolve) { //console.log('made it to the function'); promptGet(['Player1Type']).then(function(result){ if (result.Player1Type !== "X"){ this.pOneType = false;} //console.log(this.pOneType); }) .then(function(){ resolve(); }); } Game.prototype.displayPlayers = function(resolve) { if (pOneType === true){ console.log(this.playerOneName + " will be X's"); console.log(this.playerTwoName + " will be O's"); } else { console.log(this.playerOneName + " will be O's"); console.log(this.playerTwoName + " will be X's"); } console.log("Let's Get Started!"); } var test = new Game(); new Promise(function(resolve, reject){ test.getName(resolve); }) .then(function(resolve, reject){ test.getType(); }) .then(function(resolve, reject){ test.displayPlayers(); });

我知道这是非常草率的代码,但即便如此,我认为它应该工作,test.displayPlayers() test.getType() 之前执行,但事实并非如此。 谢谢你的帮助! 我也愿意听取有关如何清理代码的建议。

I am very new to NodeJS, and I am trying to use promises to prompt the user for input in a specific order. Here is my code:

var prompt = require('prompt'); var promising = require("promise-adapter"); var promptGet = promising(prompt.get); prompt.start(); function Game () { playerOneName = ''; playerTwoName = ''; pOneType = true; } //prompts the user for two names and assigns them //to player one and player to for the game object Game.prototype.getName = function (resolve){ promptGet(['playerName1', 'playerName2']).then(function(result){ this.playerOneName = result.playerName1; this.playerTwoName = result.playerName2; }) .then(function() { resolve(); }); } Game.prototype.getType = function (resolve) { //console.log('made it to the function'); promptGet(['Player1Type']).then(function(result){ if (result.Player1Type !== "X"){ this.pOneType = false;} //console.log(this.pOneType); }) .then(function(){ resolve(); }); } Game.prototype.displayPlayers = function(resolve) { if (pOneType === true){ console.log(this.playerOneName + " will be X's"); console.log(this.playerTwoName + " will be O's"); } else { console.log(this.playerOneName + " will be O's"); console.log(this.playerTwoName + " will be X's"); } console.log("Let's Get Started!"); } var test = new Game(); new Promise(function(resolve, reject){ test.getName(resolve); }) .then(function(resolve, reject){ test.getType(); }) .then(function(resolve, reject){ test.displayPlayers(); });

I know that this is very sloppy code, but even so, I think that it should work such that the test.displayPlayers() executes before test.getType(), but it is not. Thanks for any help! I am also willing to hear advice about how to clean up the code.

最满意答案

我不会说承诺是这样做的方式,但是如果你仍然想要使用它,你就会误解如何将它们用于手头的任务。

每个异步代码块都应该返回一个promise,在你的情况下,那些在等待用户输入时会被阻塞。

您可以定义返回新承诺或现有承诺的函数,并将它们相互链接,从而能够控制代码的执行顺序。

看看下面的简单小提琴。 请注意, getName返回一个新的promise,它使用Promise构造函数构造,该构造函数将执行程序作为参数,它提供promise实现的resolve和reject功能。

当您的异步代码完成时,或者在这种情况下是阻塞代码时,您只需使用或不使用已解析的值来解析promise。

默认情况下, .then()函数返回一个新的promise,如果你在.then()函数中返回一个对象,它将被自动解析,除非该对象是一个新的promise。

function Game() {
  var playerOneName = '';
  var playerTwoName = '';
  var pOneType = true;
}

//prompts the user for two names and assigns them 
//to player one and player to for the game object
Game.prototype.getName = function(resolve) {
  return new Promise(function(resolve, reject) {
    var playerOneName = prompt("Please enter your name", "Harry Potter");
    var playerTwoName = prompt("Please enter your name", "Ron Weasley");
    if (playerOneName !== null && playerTwoName !== null) {
      resolve();
    } else {
      reject();
    }
  });
}

var someOtherFunction = function() {
  alert("This is inside some other function!");
  return "A value that gets resolved by the promise!";
}


var testGame = new Game();
testGame.getName()
  .then(function() {
    alert("This happens when names have been chosen!");
  })
  .then(someOtherFunction)
  .then(function(resolvedValue) {
    alert(resolvedValue);
  }) 
  
 

从这里你应该能够获得承诺的基本内容,但我强烈建议你阅读MDN Promise文档。

I wouldn't say that promises is the way to do this, but if you still want to use it, you've misunderstood how to use them for the task at hand.

Each asynchronous code block should return a promise, and in your case those would be the blocking while waiting for the user inputs.

You define functions that return either a new promise or an existing promise and chain them onto each other, thus being able to control the execution order of your code.

Take a look at the simple fiddle below. Note that getName returns a new promise, which is constructed using the Promise constructor that takes an executor as parameter, that supplies the resolve and reject functions of the promise implementation.

When your asynchronous code is done, or in this case the blocking code, you simply resolve the promise with or without a resolved value.

By default, the .then() function returns a new promise, and if you return an object inside the .then() function, it will be automatically resolved, unless the object is a new promise.

function Game() {
  var playerOneName = '';
  var playerTwoName = '';
  var pOneType = true;
}

//prompts the user for two names and assigns them 
//to player one and player to for the game object
Game.prototype.getName = function(resolve) {
  return new Promise(function(resolve, reject) {
    var playerOneName = prompt("Please enter your name", "Harry Potter");
    var playerTwoName = prompt("Please enter your name", "Ron Weasley");
    if (playerOneName !== null && playerTwoName !== null) {
      resolve();
    } else {
      reject();
    }
  });
}

var someOtherFunction = function() {
  alert("This is inside some other function!");
  return "A value that gets resolved by the promise!";
}


var testGame = new Game();
testGame.getName()
  .then(function() {
    alert("This happens when names have been chosen!");
  })
  .then(someOtherFunction)
  .then(function(resolvedValue) {
    alert(resolvedValue);
  }) 
  
 

From this you should be able to get the basic stuff of promises, but I highly recommend that you read the MDN Promise documentation.

更多推荐

本文发布于:2023-07-28 16:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1306857.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   顺序   正确   js   Node

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!