异步方法链接? [英] Async Method Chaining?

查看:60
本文介绍了异步方法链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用异步方法链接创建一个类.但是,在我从数据库中完全获取数据之前,我仍在设置新值.我想念什么吗?

I'm trying to create a class with async method chaining. However, I'm still setting the new values before I fully fetch the data from the database. Am I missing something?

我也不想使用任何第三方模块.

I also don't want to use any third-party modules.

/* Class */

class UserDB {
    constructor() {
        this.user = {}
        this.user.username = null
    }

    set(name, value) {
        this.user[name] = value
        return this
    }

    update() {
        return new Promise((resolve, reject) => {
            const db = MongoConnection.client.db('database').collection('users')
            db.updateOne({ _id: this.user._id }, { $set: this.user}, (err, result) => {
                if (err) reject(err)
                resolve(this)
            })
        })
    }

    findByEmail(email) {
        return new Promise((resolve, reject) => {
            const db = MongoConnection.client.db('database').collection('users')
            db.findOne({ email: email }, (err, result) => {
                if (err) reject(err)
                this.user = result
                resolve(this)
            })
        })
    }
}

module.exports = UserDB


/*execution*/

new UserDB().findByEmail('email@email.com')
    .set('username', 'new_name')
    .update()

推荐答案

那确实很有趣.您可以使用将操作附加到 .then 链的方法来使返回的Promise重载:

Thats indeed interesting. You could overload the returned Promise with methods that attach the operation to a .then chain:

 class AsyncChainable {
   constructor() {
    this._methods = {};

    const that = this;
    for(const key of  Object.getOwnPropertyNames(Object.getPrototypeOf(this))) {
     this._methods[key] = function(...args) {
       return that.chain(this.then(() => that[key](...args)));
    }
  }

  chain(promise) { return Object.assign(promise, this._methods); }
}

然后在您的custon课堂中使用它:

Then use that in your custon class:

 class User extends AsyncChainable {
   login() {
    return this.chain((async () => {
     // some logic
    })());
  }
}

这样您就可以做到:

 (new User).login().login().then(console.log);

这篇关于异步方法链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆