When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log.

It seems like this behavior is expected from the function, but I'm unsure how to fix my code.

This code snippet is related to vue.js, using electron-vue and NeDB.

<template>
  <div>
    {{ testNedb3('NDId6sekw6VYLmnc')  //this is a test by adding specific id }}
  </div>
</template>

<script>
import Promise from 'bluebird'
export default {
  methods: {
    dbFindAsync2: function (db, opt) {
      return new Promise(function (resolve, reject) {
        db.find(opt, function (err, doc) {
          if (err) {
            reject(err)
          } else {
            resolve(doc)
          }
        })
      })
    },
    testNedb3: async function (id) {
      const flattenMemAsync = function (arr) {
        return new Promise(function (resolve) {
          Array.prototype.concat.apply(
            [],
            arr.map(function (arr) {
              resolve(arr.members)
            })
          )
        })
      }
      const filterByNameIdAsnc = function (arr) {
        return new Promise(function (resolve) {
          const result = arr.filter(function (member) {
            return member.nameId === id
          })
          resolve(result)
        })
      }
      this.dbFindAsync2(
        this.$db, { 'members.nameId': id }, { 'members': 1, _id: 0 }
      ).then(function (res) {
        const docs = res
        flattenMemAsync(docs).then(function (res) {
          const flatMembers = res
          filterByNameIdAsnc(flatMembers).then(function (res) {
            console.log('result', res)
            console.log('result_firstname', res[0].firstName)
            return res
          })
        })
      })
    },

this.$db fetches data from NeDB in the form of a two-dimensional array. To make it more manageable, I am trying to flatten the array with flattenMemAsync and filter out unwanted data with filterByNameIdAsnc.

The output of console.log('result', res) is an array, while

console.log('result_firstname', res[0].firstName)
returns a string.

I attempted changing the calling code from

{{ testNedb3('NDId6sekw6VYLmnc') }}
to
{{ {{ testNedb3('NDId6sekw6VYLmnc').then(value => {return value}) }}
, but the outcome remained unchanged.

I also tried

{{ await testNedb3('NDId6sekw6VYLmnc').then(value => {return value}) }}
, resulting in an error message stating "Parsing error: Cannot use keyword 'await' outside an async function."

Any suggestions would be greatly appreciated. Thank you.

Answer №1

Avoid calling an async method directly within a view.

Once you mark a method as async, it will automatically return a promise. Therefore, there is no need to both return a promise and mark it as async simultaneously.

Instead, make sure to await the async method or promise within the created hook or another appropriate lifecycle hook. Then, store the result in the component's data and render that data.

Additionally, consider checking out the vue-promised plugin for more assistance with handling promises in Vue.js.

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

Dynamic element not firing jQuery event

My question is... // Using ajax to dynamically create a table $(".n").click(function(){ var id= $(this).closest('tr').find('td.ide2').html(); //for displaying the table $.ajax({ type: 'POST&ap ...

Utilizing AJAX and PHP to refresh information in the database

For my project, I need to change the data in my database's tinyint column to 1 if a checkbox is selected and 0 if it is deselected. This is the Javascript/Ajax code I have written: <script> function updateDatabaseWithCheckboxValue(chk,address) ...

eliminating and adding a node

Is there a way to replace the existing span elements inside the div (<div id='foo'>) with newly created nodes? I have been looping through all the children of the div, using removeChild to remove each node, and then appending a new node in ...

Using absolute positioning on elements can result in the page zooming out

While this answer may seem obvious, I have been unable to find any similar solutions online. The problem lies with my responsive navbar, which functions perfectly on larger screens. However, on mobile devices, the entire website appears zoomed out like thi ...

Is there a way to make sure that ngbpopovers stay open even when hovering over the popover content?

I have implemented a ngbpopover to display user information on an element. Currently, the popover is triggered on both hover and click events, but I would like it to remain open when hovered over, instead of closing as soon as the mouse moves away. How c ...

Firing up asynchronous VuexFire data fetching using promises and error catching

Exploring the functioning vuex action called init which fetches a settings and an accounts collection: actions: { init: firestoreAction(({ bindFirestoreRef, commit }, payload) => { bindFirestoreRef( 'settings', fb.settings.doc(pay ...

Is there a built-in function in Firefox that can retrieve a list of all indexedDB names stored in the

When working in chrome, I utilized the window.indexedDB.databases() method to retrieve all indexedDb names. However, this same method does not seem to be functioning in firefox. In an attempt to resolve this issue, I will explore alternative methods such ...

Transferring values with jQuery

I attempted to customize the appearance of the select dropdown options, but unfortunately, the value of the options is not being transferred to the new jQuery-created class. Due to this issue, I am unable to achieve the desired outcome. The expected behavi ...

The Pino error log appears to be clear of any errors, despite the error object carrying important

After making an AXIOS request, I have implemented a small error handling function that is called as shown below: try { ... } catch (error) { handleAxiosError(error); } The actual error handling function looks like this: function handleAxiosError(er ...

Trouble with ES6 Arrow Functions, Syntax Error

I am encountering an issue with my JS class structure: class Tree { constructor(rootNode) { this._rootNode = rootNode; rootNode.makeRoot(); } getRoot() { return this._rootNode; } findNodeWithID(id) ...

jQuery - restrict input field based on the value of a different selected field

Could anyone recommend a jQuery plugin that can achieve the following functionality? For example: <label><input type="checkbox" depends_on="foo=5" name="boo" ... /> Check </label> <select name="foo" ... > <option value="5" se ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

Enhancing material appearance by incorporating color gradient through the extension of three.js Material class using the onBeforeCompile method

In my three.js scene, I have successfully loaded an .obj file using THREE.OBJLoader. Now, I am looking to add a linear color gradient along the z-axis to this object while keeping the MeshStandardMaterial shaders intact. Below is an example of a 2-color l ...

What makes React.js such a challenging skill to master?

Why am I struggling? After dedicating 6 months to learning React.js, I find myself overwhelmed by the multitude of chapters and feeling lost. Could you kindly share your journey with React.js in a step-by-step manner? Your advice would be greatly apprecia ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...

Postpone the processing of a message in the Service Bus Queue until a specific time using NodeJS

Despite trying multiple tutorials, I have been unable to achieve the desired result so far. Currently, my setup involves a nodejs app that sends messages to the Service Bus Queue and another nodejs app that continuously polls it. The goal is to schedule a ...

What order does JavaScript async code get executed in?

Take a look at the angular code below: // 1. var value = 0; // 2. value = 1; $http.get('some_url') .then(function() { // 3. value = 2; }) .catch(function(){}) // 4. value = 3 // 5. value = 4 // 6. $http.get('some_url') ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

When the child state changes the parent state, useEffect may not be triggered for the first time

Component for children export const FlightRange = (props) => { const [value, setValue] = useState(props.value); return ( <> <input type='range' min={1000} max={50000} step="500&quo ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...