Create an object with an asynchronous function/promise declaration

I have a function that returns an object with different functions that I can use. I want to incorporate promises into these functions for better asynchronous handling.

var DATABASE = (function () {
  var exports = {};
  
  exports.query = function(filter = {}) {
    return true;
  }

  return exports;
}());

console.log(DATABASE.query());

I attempted to make this function async, but I encountered an error stating "DATABASE.query is not a function."

var DATABASE = (async function () {
  var exports = {};
  
  exports.query = await function(filter = {}) {
      return true;
  }

  return exports;
}());

console.log(DATABASE.query());

I also tried using promises, which seemed to work fine. However, I believe using await/async would be more efficient in terms of coding.

var DATABASE = (function () {
  var exports = {};
  
  exports.query = function(filter = {}) {
    return new Promise(function(resolve, reject) {
      resolve(true);
    });
  }
  return exports;
}());

DATABASE.query().then(function(result) { 
  console.log(result);
});

Is there a way you can assist me in converting this code to utilize async/await instead?

Answer №1

To properly make your query method asynchronous, avoid using an IIFE for the module pattern which is unnecessary:

const DATA_HANDLER = (function () {
  const exports = {};
  
  exports.query = async function(filter = {}) {
//                ^^^^^
      return true;
  };

  return exports;
}());

console.log(DATA_HANDLER.query());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on incorporating the ":gt" filter from sizzle into vanilla javascript

I am currently working on adapting a jQuery plugin to be compatible with the AngularJS JQlite API, but I have encountered some challenges along the way. Here is an overview of the plugin: (function (e) { var $product = $('#product'), ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...

Creating a JSON body using a JavaScript function

I am looking to generate a JSON Body similar to the one shown below, but using a JavaScript function. { "events": [{ "eventNameCode": { "codeValue": "xyz api call" }, "originator": { "associateID": "XYZ", "formattedName": " ...

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

How to organize and reuse code efficiently with Node.js, EJS, and front-end JavaScript?

It seems that I may have chosen the wrong platform by posting this question on the 'Software Engineering' exchange: Currently, my focus is on learning the MEAN stack (I have yet to dive into Angular, so for now I am using pure vanilla JS for the ...

"Redirecting to an HTML page from the POST method is not supported in the Flask backend and Vanilla JS frontend setup

Utilizing the selected dropdown value from the frontend to perform calculations on the backend, resulting in an HTML page being returned. It's worth noting that no response is needed from the POST method, such as using return jsonify. Currently, I am ...

Using Next.js to pass fetched data as props to components

I am currently working on integrating a leaflet map into my Next.js project. The map display is already functioning with predefined latitude and longitude in the component. However, I now need to show data retrieved from my API as the longitude and latitu ...

There seems to be a hiccup in the distribution build of Angular grunt, as it is unable to locate the

While testing the build, everything runs smoothly. However, when attempting to build the distribution, an error is encountered: An error occurred: Cannot find module '/Users/matt.sich/Documents/angularProjects/firstProject/node_modules/grunt-usemin/l ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...

Numbering Tables Effectively in ReactJS

Currently working on coding a table in ReactJS and MUI, my goal is to number the No. column from 1 to the length of the array. This snippet shows my code: <TableBody> {quizes.map((quiz, index) => ( <TableRow key={quiz._id}> ...

The Express server's `GET` request at the root does not seem

When I access localhost:8080/chat?k=1&d=1, the console displays "CHAT PAGE" and everything works correctly. However, when I try to visit localhost:8080, the root event does not display "INDEX PAGE" as expected. Instead, it automatically retrieves ind ...

No response text returned from the local Ajax request

Currently, I am facing a challenge while attempting to send an ajax call from the client to my server containing data related to an input parameter. The issue is that although I can view the data in my server's console, it does not display in the brow ...

Fetching locales asynchronously in nuxt.js using i18n and axios: A step-by-step guide

I am facing an issue with getting the location asynchronously. Whenever I try to implement my code, it results in a "Maximum call stack size exceeded" error. How can I resolve this issue? Previously, I attempted to retrieve the location by using the axios ...

Tips for retrieving specific database entries using a JavaScript function

I'm currently in the process of developing a web directory that showcases organizations based on the selected county by utilizing an XML database. During testing, I have configured it to only display organization names and counties for now. However, ...

Using MongoDB and NodeJS to retrieve data from a promise

When I make a request to the database using promises, my goal is to extract the values of "latitude" and "longitude" for all documents and store them in an array. This is how I am currently approaching it: const promises = [ dbo.collection("users").f ...

Is it possible to extract the selected indexes of all select menus in my HTML and assign them to various arrays of my choosing? I find myself writing a lot of code just for one select menu

In order to determine which TV character the user most closely resembles based on their answers to a series of questions, I have created a function. However, my current code is inefficient when it comes to handling multiple select menus! I am considering i ...

Is window.open exclusive to Firefox?

Apologies if this question has been asked before! I am experiencing some issues with my Javascript code. It works perfectly in Firefox and opens a pop-up window as expected. However, in IE 9 it does nothing, and in Chrome it behaves like a link and change ...

Custom input field in Material UI not communicating properly with Redux form

I am currently utilizing Material UI and React to implement a custom input field. While using redux form for form validation, I have encountered an issue where the onBlur and onFocus events are not being dispatched successfully. Interestingly, if I switch ...

JavaScript function failing to properly handle PHP array input

I am facing an issue with a PHP array that I am trying to pass to a JavaScript function using "json_encode($array)". Every time I click the button to trigger the function, the page simply refreshes without any action being taken. I have attempted to troub ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...