question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to return the promise for further usage.

See original GitHub issue

Hello!

I’m somewhat new to promises and stuff regarding this so… I did a small DB module which I’m importing wherever I need it.

var DB = function() {
    this.pool = require('mysql2').createPoolPromise({ host: '', user: '', password: '', database: '' });
}

DB.prototype.query = function( sql, format ) {
    this.pool.getConnection().then( conn => {
        var result = conn.query( sql , format );
        conn.release();
        return result;
    }).catch( err => {
        console.log( err );
    });
}

module.exports = new DB();

Now, in another module, I’m requiring the DB.js module as follows

var db = require( './controllers/DB.js' );

How I would like to use it is as follows:

db.query( 'SELECT * FROM users WHERE id = ? LIMIT 1', [ 5 ] ).then( result => {
     console.log( result );
});

Though everything “seems” to be working, I’m having an error as follows:

TypeError: Cannot read property 'then' of undefined

What am I doing wrong ? I guess that the result var is not a Promise type of object ? If so, what should I return in order to chain the result in other modules.

Thank you

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
sidorarescommented, Jun 17, 2016

first of all I suspect that inner loop might be removed with some kind of join

if you want to call cb( merchant ); only after all inner loop promises are resolved you can use something like this

db.query( 'SELECT * FROM merchants WHERE id = 5' )
    .then( ([ rows, columns ]) => {
        var merchant = rows[0];
        merchant.shops = [];
        return merchant;
    })
    .then( merchant => {
         var products = [];
         var orders = [];
         db.query( 'SELECT * FROM shops WHERE merchantID = ?', [ merchant.id ] )
          .then([shops] => {
              products = shops.map( shopId => db.query( 'SELECT * FROM products WHERE shopID = ? ORDER BY name ASC', shopId );
              orders = shops.map( shopId => db.query( 'SELECT * FROM products WHERE shopID = ? ORDER BY name ASC', shopId );
             Promise.all(products)
                .then( products => /* do something with products */ )
                .then( () => {
                     Promise.all(orders).then(
                        // all ready, call callback?
                     );
                 }


          });

there might be better solution, I personally prefer traditional callbacks or async library and not very experienced in promise patterns

also instead of using loops to append array I’d use something like this

    var arr1 = [1, 2, 3];
    var arr2 = [3, 4, 5];
    console.log(arr1.concat(arr2)); // instead of for (var i=0; i < arr2l ++i) { arr1.push(arr2[i]); }
0reactions
sidorarescommented, Jun 16, 2016

it’s not wasted, you still learned something 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Promise - JavaScript - MDN Web Docs
As these methods return promises, they can be chained. ... See the Microtask guide to learn more about how these methods use the...
Read more >
How to return many Promises and wait for them all before ...
You can use Promise.all (spec, MDN) for that: It accepts a bunch of individual promises and gives you back a single promise that...
Read more >
Javascript: How to access the return value of a Promise object
1 - .then() chaining · 2 - Use returned value later in a code.
Read more >
How do I make a JavaScript promise return something other ...
Promises don't "return" values, they pass them to a callback (which you supply with .then()). The spec simply sounds confused to me. It's...
Read more >
JavaScript Promise Tutorial – How to Resolve or Reject ...
Promise.race([promises]) – It waits for the first (quickest) promise to settle, and returns the result/error accordingly. Promise ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found