令人窒息的操作,nodejs面向对象。



// async函数返回一个 Promise 对象,可以使用then方法添加回调函数。
// 当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。
class Demo {
    //构造函数
    constructor(x, y) {
        this.x = x //类中变量
        this.y = y
    }

    add = () => { //普通函数返回x+y的和
        return this.x + this.y
    }
    sleep = time => {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve('ok')
            }, time);

        })
    }
    //async 用于申明一个 function 是异步的,所以在该function里面的程序都是异步的
    start = async () => {
        let result = await this.sleep(1000)//await后面可以接着一个直接变量或者是一个promise对象
        let sum = this.add()
        console.log("了解", sum)
        return result
    }
}

let demo = new Demo(2, 3)
demo.start().then(m => {
        console.log(m);
    }
);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM