Nodejs Async/await Not Working As Expected
I have an express API that reads from my fauna database. I have a class setup called Database that handles all my fauna queries, and an async method called getQuotes that essentially gets a fauna document, the general structure is like this:
async getQuotes() {
// note, `query` is an async function
const doc = this.client.query(...).then((res) => {
const data = ...; // to keep this short I'm not gonna show this
console.log("faunadb handler: " + data); // just for debug
return Promise.resolve(data);
})
}
Then when I start the express API, I have it call the getQuotes method and log the data (just for debug).
const quotes = db.getQuotes().then((quotes) => {
console.log("fauna consumer: " + quotes);
})
Now, when I run the app, I get the following output:
starting server on port.... ussual stuff
fauna consumer: undefined
faunadb handler: { ... }
The fauna consumer code runs before we actually get the promise from the fauna query API. I need to use .then because node for some reason doesn't allow me to use await. Does anyone know how to solve this? Thank you!
(using node version v16.14.0
, running on Arch Linux
)
Answer
You aren't returning anything from your getQuotes()
function. The return in your callback is only going to return from the callback, not from the enclosing function. You also aren't awaiting anywhere, which means your async function is not going to actual wait on the result of your query.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM