sigil
sigil

Reputation: 9556

Why does my Promise return a database row in some cases but not in others?

I have a function in a module db that uses node-postgres to insert a new row into a database:

module.exports={addUser: function(phonenumber){
        return new Promise(function(resolve,reject){
            queryStr='insert into users (phonenumber,status,exitStatus) values (\''+phonenumber+'\') returning *';
            pool.query(queryStr,(err,res)=>{
                if (err){
                    reject(err);
                }
                else{
                    resolve(res);
                }
            });
        });

    }
}

When I call it like this:

var number=123456789;
testAddUser(number);

function testAddUser(phonenumber){
    db.addUser(phonenumber).then(val=>{console.log(val.rows[0])});
}

Then it successfully outputs the returned row to the console log:

anonymous {
  id: 25,
  phonenumber: '123456789'}

Which is what I want.

But when I call it like this, from within another Promise-returning function's then:

db.someOther_promise(num).then(value=>{
            doSomeStuff();
            return db.addUser(num);
    }).then(value=>{
        console.log("value "+value.rows[0]);
    })

Then I only get the output:

value [object Object] 

That makes me wonder if maybe someOther_promise() is completing and starting the .then() resolution before the db.addUser(num) call completes. But I thought that returning a promise means that the second .then() has to wait for the promise created by the return value of the first .then() to complete.

Upvotes: 0

Views: 40

Answers (1)

ewcz
ewcz

Reputation: 13097

It seems to me that this has nothing to do with Promises. When you do

console.log("value "+value.rows[0]);

you are converting value.rows[0] to string which then outputs value [object Object]. If you use console.log("value ", value.rows[0]) instead, you should see the desired output...

Upvotes: 3

Related Questions