在构造函数中等待其他函数结束

Waiting for other function to end in constructor function

我有Child的这种类型的构造函数。函数 play 必须在每一秒后减少饥饿并增加乐趣,这被作为参数。如果乐趣为 10 或饥饿为 1,则必须停止。 功能 need 必须 return 当前的乐趣和饥饿感。如果我想等待 play() 如果有任何待处理,我有一个问题如何去做,就像在我的代码中一样。你能帮忙吗? play 中的参数决定了 child 播放的秒数 - 例如如果有3个,乐趣会增加+3

function Person(firstName, lastName, age, type, hunger) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.type = type;
    this.hunger = hunger;
}

function Child(firstName, lastName, age, type, hunger) {
    Person.call(this, firstName, lastName, age, type, hunger)
    this.fun = 5
}
Child.prototype = Object.create(Person.prototype)
    Child.prototype.constructor = Child

    Child.prototype.play = async function (sec) {

    const interval = setInterval(() => {
        if (this.fun >= 10 || this.hunger <= 1) {
            clearInterval(interval)
        } else {
            this.fun += 1
            this.hunger -= 1
        }
    }, 1000)

        setTimeout(() => clearInterval(interval), sec * 1000)
}
Child.prototype.need = async function () {
    await this.play()
    return "Fun: " + this.fun + " , hunger: " + this.hunger
}

const child1 = new Child("child1", "childdddd", 3, 'boy', 4)

child1.play(3)

console.log(child1.need())

您的代码运行完美,但 async 函数 return 和 Promise,因此您必须:

  • then
  • 中提供回调
  • await

function Person(firstName, lastName, age, type, hunger) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.type = type;
    this.hunger = hunger;
}

function Child(firstName, lastName, age, type, hunger) {
    Person.call(this, firstName, lastName, age, type, hunger)
    this.fun = 5
}
Child.prototype = Object.create(Person.prototype)
Child.prototype.constructor = Child

Child.prototype.play = function (sec) {
    this.result = new Promise(resolve => {
        const interval = setInterval(() => {
            if (this.fun >= 10 || this.hunger <= 1) {
                end();
            } else {
                this.fun += 1
                this.hunger -= 1
            }
        }, 1000)
        
        setTimeout(end, sec * 1000)
        
        function end() {
            clearInterval(interval)
            resolve()
        }
    })
}
Child.prototype.need = async function () {
    await this.result;
    return "Fun: " + this.fun + " , hunger: " + this.hunger
}

const child1 = new Child("child1", "childdddd", 3, 'boy', 4)

child1.play(3)

child1.need().then(console.log);