Async Method Chaining? [duplicate]










0
















This question already has an answer here:



  • JS - chain async methods in sequence w/o callback or modification

    3 answers



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()









share|improve this question















marked as duplicate by charlietfl, Heretic Monkey, Bergi javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Nov 12 '18 at 21:20


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • Async functions return Promises, so you can't really chain them like that without changing the Promise class itself. Why do you think you need these functions to be async?

    – Lee Daniel Crocker
    Nov 12 '18 at 21:19











  • well... You can chain async methods like this, but, it would have to work in such a way that what you're actually doing is setting up a chain of things that you want to occur. For xmaple, .set() wouldn't be able to directly access the results of fetchData because set() will run before fetchData() has completed its async action. The setup of such a system would very much follow the existing information you've found WRT chaining using the this keyword.

    – Kevin B
    Nov 12 '18 at 21:20











  • See also stackoverflow.com/a/43880581/1048572

    – Bergi
    Nov 12 '18 at 21:21











  • @LeeDanielCrocker I was thinking more of using callbacks. I seen many modules use chained methods for async operations for manipulating the database.

    – Owenimus
    Nov 12 '18 at 21:22











  • Right, there's db modules that let you build a query by chaining a few methods, then execute the query by calling .exec(). That would be done using the this keyword or similar setup.

    – Kevin B
    Nov 12 '18 at 21:22
















0
















This question already has an answer here:



  • JS - chain async methods in sequence w/o callback or modification

    3 answers



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()









share|improve this question















marked as duplicate by charlietfl, Heretic Monkey, Bergi javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Nov 12 '18 at 21:20


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • Async functions return Promises, so you can't really chain them like that without changing the Promise class itself. Why do you think you need these functions to be async?

    – Lee Daniel Crocker
    Nov 12 '18 at 21:19











  • well... You can chain async methods like this, but, it would have to work in such a way that what you're actually doing is setting up a chain of things that you want to occur. For xmaple, .set() wouldn't be able to directly access the results of fetchData because set() will run before fetchData() has completed its async action. The setup of such a system would very much follow the existing information you've found WRT chaining using the this keyword.

    – Kevin B
    Nov 12 '18 at 21:20











  • See also stackoverflow.com/a/43880581/1048572

    – Bergi
    Nov 12 '18 at 21:21











  • @LeeDanielCrocker I was thinking more of using callbacks. I seen many modules use chained methods for async operations for manipulating the database.

    – Owenimus
    Nov 12 '18 at 21:22











  • Right, there's db modules that let you build a query by chaining a few methods, then execute the query by calling .exec(). That would be done using the this keyword or similar setup.

    – Kevin B
    Nov 12 '18 at 21:22














0












0








0









This question already has an answer here:



  • JS - chain async methods in sequence w/o callback or modification

    3 answers



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()









share|improve this question

















This question already has an answer here:



  • JS - chain async methods in sequence w/o callback or modification

    3 answers



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()




This question already has an answer here:



  • JS - chain async methods in sequence w/o callback or modification

    3 answers







javascript node.js asynchronous






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 22:41







Owenimus

















asked Nov 12 '18 at 21:15









OwenimusOwenimus

13




13




marked as duplicate by charlietfl, Heretic Monkey, Bergi javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Nov 12 '18 at 21:20


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by charlietfl, Heretic Monkey, Bergi javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Nov 12 '18 at 21:20


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • Async functions return Promises, so you can't really chain them like that without changing the Promise class itself. Why do you think you need these functions to be async?

    – Lee Daniel Crocker
    Nov 12 '18 at 21:19











  • well... You can chain async methods like this, but, it would have to work in such a way that what you're actually doing is setting up a chain of things that you want to occur. For xmaple, .set() wouldn't be able to directly access the results of fetchData because set() will run before fetchData() has completed its async action. The setup of such a system would very much follow the existing information you've found WRT chaining using the this keyword.

    – Kevin B
    Nov 12 '18 at 21:20











  • See also stackoverflow.com/a/43880581/1048572

    – Bergi
    Nov 12 '18 at 21:21











  • @LeeDanielCrocker I was thinking more of using callbacks. I seen many modules use chained methods for async operations for manipulating the database.

    – Owenimus
    Nov 12 '18 at 21:22











  • Right, there's db modules that let you build a query by chaining a few methods, then execute the query by calling .exec(). That would be done using the this keyword or similar setup.

    – Kevin B
    Nov 12 '18 at 21:22


















  • Async functions return Promises, so you can't really chain them like that without changing the Promise class itself. Why do you think you need these functions to be async?

    – Lee Daniel Crocker
    Nov 12 '18 at 21:19











  • well... You can chain async methods like this, but, it would have to work in such a way that what you're actually doing is setting up a chain of things that you want to occur. For xmaple, .set() wouldn't be able to directly access the results of fetchData because set() will run before fetchData() has completed its async action. The setup of such a system would very much follow the existing information you've found WRT chaining using the this keyword.

    – Kevin B
    Nov 12 '18 at 21:20











  • See also stackoverflow.com/a/43880581/1048572

    – Bergi
    Nov 12 '18 at 21:21











  • @LeeDanielCrocker I was thinking more of using callbacks. I seen many modules use chained methods for async operations for manipulating the database.

    – Owenimus
    Nov 12 '18 at 21:22











  • Right, there's db modules that let you build a query by chaining a few methods, then execute the query by calling .exec(). That would be done using the this keyword or similar setup.

    – Kevin B
    Nov 12 '18 at 21:22

















Async functions return Promises, so you can't really chain them like that without changing the Promise class itself. Why do you think you need these functions to be async?

– Lee Daniel Crocker
Nov 12 '18 at 21:19





Async functions return Promises, so you can't really chain them like that without changing the Promise class itself. Why do you think you need these functions to be async?

– Lee Daniel Crocker
Nov 12 '18 at 21:19













well... You can chain async methods like this, but, it would have to work in such a way that what you're actually doing is setting up a chain of things that you want to occur. For xmaple, .set() wouldn't be able to directly access the results of fetchData because set() will run before fetchData() has completed its async action. The setup of such a system would very much follow the existing information you've found WRT chaining using the this keyword.

– Kevin B
Nov 12 '18 at 21:20





well... You can chain async methods like this, but, it would have to work in such a way that what you're actually doing is setting up a chain of things that you want to occur. For xmaple, .set() wouldn't be able to directly access the results of fetchData because set() will run before fetchData() has completed its async action. The setup of such a system would very much follow the existing information you've found WRT chaining using the this keyword.

– Kevin B
Nov 12 '18 at 21:20













See also stackoverflow.com/a/43880581/1048572

– Bergi
Nov 12 '18 at 21:21





See also stackoverflow.com/a/43880581/1048572

– Bergi
Nov 12 '18 at 21:21













@LeeDanielCrocker I was thinking more of using callbacks. I seen many modules use chained methods for async operations for manipulating the database.

– Owenimus
Nov 12 '18 at 21:22





@LeeDanielCrocker I was thinking more of using callbacks. I seen many modules use chained methods for async operations for manipulating the database.

– Owenimus
Nov 12 '18 at 21:22













Right, there's db modules that let you build a query by chaining a few methods, then execute the query by calling .exec(). That would be done using the this keyword or similar setup.

– Kevin B
Nov 12 '18 at 21:22






Right, there's db modules that let you build a query by chaining a few methods, then execute the query by calling .exec(). That would be done using the this keyword or similar setup.

– Kevin B
Nov 12 '18 at 21:22













1 Answer
1






active

oldest

votes


















0














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);



Then use that in your custon class:



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




That way you can do:



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





share|improve this answer





























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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);



    Then use that in your custon class:



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




    That way you can do:



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





    share|improve this answer



























      0














      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);



      Then use that in your custon class:



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




      That way you can do:



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





      share|improve this answer

























        0












        0








        0







        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);



        Then use that in your custon class:



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




        That way you can do:



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





        share|improve this answer













        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);



        Then use that in your custon class:



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




        That way you can do:



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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 '18 at 21:26









        Jonas WilmsJonas Wilms

        56.7k42851




        56.7k42851













            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo