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> }
CodePudding user response:
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));