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

How can React Native efficiently retrieve data from multiple APIs simultaneously?

In my current project, I am incorporating multiple APIs that are interlinked with each other by sharing the same data structure... Below is the code snippet: export default class App extends React.Component { constructor(props) { super(props); } ...

How do I make the YouTube Grid Gallery player show up in a pop-up window?

I have been experimenting with the following code: <head> <script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script> <script type="text/javascript"> function loadVideo(playerUrl, ...

Experiencing difficulty importing Materialize CSS JS into React

Good day everyone, I've been facing challenges in implementing materialize css into my react-app, specifically with the JavaScript files. After trying various methods, I believe that I have made some progress using the following approach: In my &ap ...

Express JS encountering Firebase Google Sign-In glitch

Whenever a user clicks a button on the HTML page, this function is triggered. The function resides in auth.js and it is called from the server.js page. auth.js const firebase = require("firebase"); static googleSignIn(req,res){ firebase.aut ...

When using node.js and express, attempting to send an email with the packages 'nodemailer' and 'nodemailer-handlebars' may result in a TypeError being thrown, specifically [ERR_INVALID_ARG_TYPE]

I am encountering an issue while attempting to send an email using an HTML template located in the 'view' folder within the same path. The HTML template is named 'index.handlebars'. Despite believing that the path is correct, I am recei ...

The scale line on the OpenLayers map displays the same metrics twice, even when the zoom level is different

When using the Openlayers Map scale line in Metric units, a specific zoom rate may be repeated twice during the zoom event, even though the actual zoom-in resolution varies on the map. In the provided link, you can observe that the zoom rates of 5km and ...

What kind of type is recommended to use when working with async dispatch in coding?

For my TypeScript and React project, I am currently working on an action file called loginAction.tsx. In this file, there is a specific line of code that handles the login functionality: export const login = (obj) => async dispatch => { dispatch( ...

Leveraging the useRef hook to adjust the CSS styling of a React component

Currently, I am working on changing the style of a react component by utilizing the useRef hook. So far, I have implemented the useRef hook to reference the specific component whose style I want to modify when clicking on two buttons. Despite my efforts, I ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

Tips for attaching a "progress" and refresh event to an ajax call while sending a file

I am currently using the FormData API and AJAX to upload files to a server in PHP-CodeIgniter. The file upload works perfectly when triggered by the file select event. However, I would like to display a progress bar next to each file being uploaded with th ...

Error: The function expressJwt is not recognized as a valid middleware

As I delve into learning about middlewares, I encountered an issue when trying to import express-jwt. The syntax I used was: const expressJwt = require('express-jwt') To address the problem, I uninstalled the current version of express-jwt and i ...

Trigger is not activated by dynamically created element

I am dealing with a block of code that is dynamic and looks like this. var li3 = document.createElement('li'); li3.classList.add("col-sm-3"); li3.classList.add("no_padding"); var inner = ""; inner = inner ...

Conceal a column within a table by double-clicking

I'm working on a project with a table, and I'd like to implement a feature where a column hides when double-clicked. I've seen various solutions for hiding columns on Stack Overflow, but I could use some guidance on where to add the ondblcli ...

Is there a method to update the res object following a couchbase DB call without encountering the error "Error: Can't set headers after they are sent"?

let express = require('express'); let searchRoute = express.Router(); searchRoute.get('/', function(req, res, next) { console.log('1'); databaseCall(function(error, result) { if (error) { res.sta ...

Visual Studio Code is not properly highlighting imports for Vue 3 using the Composition API

Upon careful examination, it is evident that the import is not highlighted despite the utilization of the component SearchBar. https://i.stack.imgur.com/G4sAm.png Various attempts have been made to rectify this issue including the installation of the Vet ...

Utilizing Vue's looping functionality to dynamically insert CSS class names

As a newcomer to Vue, I am facing an issue with handling an array of objects. My goal is to dynamically assign a className to the wrapper of a loop based on a condition. For instance: <div v-for="({time, date, name}, i) in myObject" :key=" ...

Issue with PLUploader in ASP.Net/JQuery: "Add Files" button not functioning post image upload操作

Hello, I've been utilizing the PLUploader controller for ASP.NET in C#. Initially, it works as intended, but after uploading files, the "add files" button becomes disabled or stops working, preventing me from adding more images. Can anyone offer assi ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

HighCharts fails to display on Polymer webpage

I am working on a project that involves using Polymer alongside HighCharts. Here is the code I have implemented: HTML : <div class="container" layout vertical center> <paper-shadow z="1" class="span-shadow"> <post-card id ...

Transforming dates from JSON and showcasing them on a DataTable

I'm facing an issue with my local JSON file where the dates are being rendered in a DataTable as /Date(1350028800000)/ (10/12/2012). I came across this thread which talks about converting the date format, but I need help figuring out how to implement ...