0

I was hoping someone could help me make sense of why the following code isn't working properly.

In the Expense Data class, I have a function listExpenses which should only return data once the promise is either resolved or rejected.

However, when I instantiate a new expenseData object and then try to log a list of expenses, I get a pending Promise. I would have expected the Promise to always be resolved at this stage.

class ExpenseData {
  constructor() {
    this.client = new Client({ database: 'expenses' })
  }

  async listExpenses() {
    await this.client.connect().catch(err => logAndExit(err));
    let data = await this.client.query("SELECT * FROM expenses ORDER BY created_on ASC")
                                .catch(err => logAndExit(err))
    return data;
  }
}
let expenseData = new ExpenseData(); 
let myData = expenseData.listExpenses();
console.log(myData);

Here's what I get in my console after running this code: Promise { <pending> }

bugsyb
  • 5,662
  • 7
  • 31
  • 47
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Matt Morgan Nov 17 '21 at 16:41
  • 2
    your method is async, but you do not await it. `let myData = await expenseData.listExpenses();` ? – Alexey Zelenin Nov 17 '21 at 16:43
  • `let x = await ...; return x;` behaves the same as `return ...` – Mulan Nov 17 '21 at 18:39

1 Answers1

1

Your method is asynchronous meaning it immediately returns a Promise that will be resolved or rejected depending on what will happen in the method's body.

You need to either do this:

const func = async () => {
  let expenseData = new ExpenseData(); 
  let myData = await expenseData.listExpenses();
  console.log(myData);
};

func();

Or this:

let expenseData = new ExpenseData(); 
expenseData.listExpenses().then((myData) => console.log(myData));
Anton Nevsgodov
  • 299
  • 1
  • 7