Function async not returning the value once it retrieves data from Firebase

I have been working on a project where I am trying to return a value to app.js without having the promise processed. However, when I run the code, it returns undefined. Any suggestions on how to improve this?

export.js `

const admin = require('firebase-admin')
const db = admin.firestore();
const ref = db.collection('Things')

async function retrieveName(ting) {
  return await ref.get().then(doc => {
   doc.forEach(documentSnapshot => {
    var data = documentSnapshot.data()
    if (ting == data.name || ting == data.id) {
     return data.name
    }
   })
 })
};

module.exports.getName = function(ting) {
  retrieveName(ting).then(value =>{
    console.log(value)
    return value;
  })
};

app.js

 const exp = require('./export.js')
 var name = await exp.getName('foo')
 console.log(name)

Answer №1

To retrieve the promise generated within your module.exports.getName function, you must do so in the following manner:

module.exports.getName = function(input) {
    return getNameValue(input).then(result =>{
        console.log(result)
        return result;
    });
};

Subsequently, within the app.js script, it is imperative to invoke the exported function from an async function (as otherwise utilizing await would not be feasible):

const exp = require('./export.js')
async function initiate() {
    var nameResult = await exp.getName('sample')
    console.log(nameResult);
}
initiate();

Answer №2

Hugo may be correct, however there is another error present aside from that. The function getNameV does not even return a promise that retrieves the value you are seeking. Instead, return data.name simply exits the anonymous function utilized in forEach(). Consequently, this value does not get passed into the promise returned by getNameV. Currently, it just generates a promise containing undefined.

Furthermore, using return await [promise] is unnecessary in this context. You can simply use return [promise], without having to label getNameV as asynchronous with async.

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

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

Guide on how to retrieve a value from a function in React Native

This method retrieves the token data from the API I am utilizing. // api.js var token=""; const getToken = { getTokenData: function(){ fetch("myurl/api/token", { method: "POST", headers: { Accept: "application/json", ...

Troubleshooting the unsuccessful outcome of the node js async.map function

Context I am new to working with Node.js and the async module. I am encountering difficulties with making synchronous calls to my redis database. Objective My ultimate goal is to return a JSON object when the user calls my REST API's GET method. Th ...

What's the best way to integrate Bootstrap into my HTML document?

Hey there, I'm new to the coding world and just started learning. I could use some assistance with including Bootstrap v5.1 in my HTML code. The online course I'm taking is using an older version of Bootstrap, so I'm having trouble finding t ...

Encountering an unexpected token error in React.js

As a new learner of React, I am still getting acquainted with JavaScript. It has been my first week attempting to import React, and finally adding the CDN script tag into my index.html. Normally, I can easily add XML tags into JS files, but when trying to ...

What is the most efficient way to minimize the use of if statements in an Angular component when calling a specific function?

Currently, I am working on an Angular 7 temperature conversion application. Within my formGroup, there are inputs and outputs along with two multi-select dropdowns where users can choose the unit of temperature 'From' and 'To' for conve ...

Automatically populate form fields with locally stored data

I am currently integrating questions from a JSON file into my EJS template and aiming to fill each field with data from localStorage. The code snippet below demonstrates how the last values of dropdown menus, text inputs, and sliders are stored: var selec ...

How can you enable a button to be clicked from within a drawer?

Hey there, I've got a div that toggles hide/show like a drawer when clicked. When the drawer is in show state, it contains a button. How can I make the button clickable without toggling the drawer? Any ideas on this?! `zIndex` doesn't seem to be ...

Incorporate a horizontal scrollbar feature within an HTML section

Currently, I am in the process of learning vue js and would like to create a layout that includes two sections. The first section should occupy 3 grids on the screen, be fixed, and not scrollable, with a division into 4 vertical parts. The second section s ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Having trouble with non-functional binary code in jQuery AJAX

Having trouble with my image upload function code. The variable is not getting posted via ajax, any assistance would be appreciated. <script type="text/JavaScript"> $(document).ready(function() { $("#btn").click(function() { $.get("i.png ...

Adding 2-dimensional text to a specified location with the help of three.js

let startPosition = new THREE.Vector3(-5,0,0); let targetPosition = new THREE.Vector3(-5,2,0); let directionVector = new THREE.Vector3().sub(targetPos,startPosition); let arrowHelper = newTHREE.ArrowHelper(directionVector.clone().normalize(),startPosition, ...

Issue with Endless scroll functionality and retaining the previous scroll position

Have you ever noticed on platforms like Pinterest or other websites that when you scroll through multiple pages and click on an image or product, then press the back button, you are taken back to the last page you viewed, along with the exact position of t ...

Utilizing LocalForage's asynchronous `getItem()` method involves awaiting the retrieval of two variables before completing the loading process

I'm still getting the hang of working with asynchronous Javascript calls and handling promises. It's a shift from my usual mindset of Do This, Wait for This. Currently, I'm utilizing localforage on my website and need to retrieve data from ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

The element vanishes from sight after being detached and re-appended

Currently, I am utilizing hQuery's draggable and droppable features. My goal is to move an element from its original parent to its new dropped parent after dragging it. However, when I detach and append the element, it seems to disappear! What could ...

Leveraging react-redux-firebase for integrating cloud functions into React JS applications

I recently started learning React JS and I'm working on a project where I need to display data from cloud firestore. To fetch the data, I am utilizing react-redux-firebase. It's all working smoothly so far. However, now I want to switch to retrie ...

NGINX, Node 8.11, and Angular 6 experiencing issues with asset routing

One issue we are facing is with getting assets to load properly in our current setup. We are using NGINX, Node 8.11, and Angular 6. In summary, I had to perform some request parsing in our Node server.js in order to ensure that files loaded correctly for ...

Having trouble building a random number guesser in JavaScript - encountering a syntax error. Does anyone have a solution?

My unique code is shown below: function ComputerGuess(){ let Guess = Math.floor(Math.random() * 10) + 1 UserPick() } function UserPick(){ let Number = prompt('Select a number between 1 - 100') if (Number > Guess){ alert('Try ...

What is the best way to implement two dropdown filters using Bootstrap 4 in an HTML document?

I am currently designing a website with a 'projects' page where clients can view all completed projects. The client now wants to add two filters: one for the 'type of service' and one for the 'type of structure'. I attempted ...