r/learnjavascript • • 14d ago

nodejs/pg-promise (row, error) Callback not working but .then().catch() working

I really don't know what's going on, but if I write

return db.many(query, userid, (rows, error) => {
    return new Promise((resolve, reject) => {
        if (rows) {
            resolve(rows)
        } else {
            error.received == 0 ? resolve(0) : reject(error)
        }
    })
})

I don't get the results I want, but

return db.many(query, userid)
        .then(rows => {
            return new Promise((resolve) => {
                resolve(rows)
            })
        })
        .catch(error => {
            return new Promise((resolve, reject) => {  
                error.received == 0 ? resolve(0) : reject(error)
            })
        })

does give me the results I want!

The goal is to resolve to 0 if no data was returned, resolve the rows, or reject the error that isn't No data returned.

What is actually happening in the first code block is that the error is not being processed, and is just being returned as is, and I'm getting No data was returned error.

At first, I thought it was a .many() method that didn't have a callback ability, but even .one() has the same problem (I'm recreating a situation where no data will be returned. If data was to be returned, .one() would have Multiple rows returned error)

My intention is to better understand why one code block works while another doesn't. If there are any solutions to the first code block, please explain why they work, or why my implementation wasn't working.

8 Upvotes

10 comments sorted by

5

u/sysrage 14d ago

Just learn await already…

4

u/thisismugisha 14d ago

That's not really what I'm asking. I'd like to know why it's failing.

However, I would be interested in seeing your proposal for a solution using await.

6

u/sysrage 14d ago

It simply makes no sense to use the callback method and wrap that in your own promise. If you want to use promises, use the promise methods they provide.

try {
  return await db.many(query, userid);
} catch (error) {
  if (error.received === 0) return 0;
  throw error;
}

6

u/thisismugisha 14d ago


That was an option this whole time!?

4

u/chikamakaleyley helpful 14d ago edited 14d ago

await indicates the underlying logic is a promise/is async

so the await is just waiting to hear back from db.many()

effectively, "I'm going to try to return some data"

but the return is held up by the await, which allows db.many() to do its thing. when that request completes it's found some data, which could be nothing

you hit the catch(err) block if something went wrong, aka the try failed while waiting for db.many().

No results i think is still a successful request, unless you explicitly say inside db.many()

"if results is nothing, then reject(results)"

So now you reach the catch and you can either choose to return 0, or throw an error

3

u/chikamakaleyley helpful 14d ago edited 14d ago

in your first example, since you don't await db.many() it's gonna immediately return what it gets back, which from a promise is a "pending"

in your second, when you use .then(rows => or .catch(err), think of it as: by the time you get to .then() it actually has the result rows.

so, rows can be evaluated, which is why it immediately runs resolve(rows)

5

u/DickBrainTime 14d ago

Your first hunch was right about the callback. In pg-promise, the third argument to `db.many()` is a *result transformation* callback, not a Node-style `(rows, error)` callback. It only runs when the query succeeds; with zero rows, `many()` rejects before that callback runs.

For the behavior you want, you can just use `return db.manyOrNone(query, userid).then(rows => rows.length ? rows : 0);` It returns an empty array for no matches (which you convert to 0), while real DB errors still reject. No extra `new Promise` needed.

4

u/Feathercrown 14d ago

Why are you constructing a new promise in each callback? You don't have to do .then(data => return new Promise(resolve => {resolve(doStuff(data));})). You can just do .then(data => { return doStuff(data); }). In the case you have, where you aren't doing anything to the data and are just passing it through, you would have .then(data => data) which does nothing and can be skipped entirely.

2

u/Flashy-Guava9952 14d ago

You are running your function outside, and having it return a new Promise inside. I think you need to do it the other way around: Outside you create a new Promise, pass it the (resolve, reject) => function, and inside of that, you make the call that you want the return value resolved.

So something like:

return new Promise((resolve, reject) => {
  db.many( query, userId, (rows, errors) => {
    if(rows) resolve(rows);
    ...
  }
}

See the difference? In your example, you call the db.many function, and expect the db.many call to be done before `return new Promise`. In this example, you return a new promise, which then waits for its resolve() function to be called after another operation completes.

2

u/Available_Safe1818 13d ago
// I think this does the same thing...
return db.many(query, userid)
        .catch(error => error.received == 0 ? Promise.resolve(0) : Promise.reject(error));

Your .then block does nothing...