0

I am using pg-promise:

class Test{
    constructor(){
        this.a = db.any('SELECT * FROM test');
    }
}

If I call test.a, it will return Promise { <pending> } }.

How do I handle this problem? I cannot use .then() to solve this problem, because I hope the value can be stored in this.a before return.

Neverever
  • 15,890
  • 3
  • 32
  • 50
SinLok
  • 589
  • 1
  • 5
  • 19

2 Answers2

0

You need to have a variable, foo, that is initialized as empty, then have the promise success function set the value of foo to the asynchronous result.

Steven McConnon
  • 2,650
  • 2
  • 16
  • 21
0

I cannot use .then() to solve this problem, because I hope the value can be stored in this.a before return.

This is a contradictory statement. If you need the value inside the constructor, you have to use then. Otherwise, you can use then later, like this:

var t = new Test();
t.a.then(data => {});

or

const t = new Test();
const data = await t.a;
vitaly-t
  • 24,279
  • 15
  • 116
  • 138