Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning an unresolved promise (async/await) in javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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> }

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading