【问题标题】:Waiting for other function to end in constructor function等待其他函数以构造函数结束
【发布时间】:2021-05-30 17:50:21
【问题描述】:

我有这种类型的Child 构造函数。功能游戏必须在每一秒之后减少饥饿并增加乐趣,这被作为一个参数。如果乐趣为 10 或饥饿为 1,则必须停止。 函数need 必须返回当前的乐趣和饥饿。如果我想等待play(),如果有任何待处理,我有一个问题,就像在我的代码中一样。你能帮忙吗? play 中的参数决定了孩子玩了多少秒 - 例如如果有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())

【问题讨论】:

  • 你不能。 JS 是单线程的。所以你必须要么使用承诺要么使用回调
  • 看不出这跟构造函数有什么关系?
  • 谢谢你们,答案在下面:)

标签: javascript oop prototype prototypal-inheritance


【解决方案1】:

您的代码运行良好,但 async 函数返回 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);

【讨论】:

  • 如果我想等待,我该怎么办?
  • await child1.need() 但它需要将周围的函数声明为async 或您的运行时环境以支持顶级await
  • 我明白了,所以最好是“then”。
  • 两者是等价的,只是代码外观的问题,也取决于你如何调用这段代码。
  • 因为你有两个play调用,一个在顶层,一个在need内部
猜你喜欢
  • 2019-01-06
  • 2019-01-31
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
相关资源
最近更新 更多