Invoking an async/await function and retrieving a result

Within an API library function, I am utilizing firestore to fetch data. This aspect of the code is functioning correctly:

export const getUserByReferrerId = async id => {
  let doc = await firestore
    .collection(FIRESTORE_COLLECTIONS.USERS)
    .where('grsfId', '==', id)  
    .get()  
    .then(querySnapshot => {
      if (!querySnapshot.empty) {
        console.log("we found a doc");
        // accessing only the first document, though there might be more
        const snapshot = querySnapshot.docs[0];
        console.log("snapshot", snapshot.id);
        return snapshot.id;  // extracting user's uid
      }
    });
}

From within a component, I am invoking this library. There is another function triggered by a button click, and I am struggling with capturing the value from the async api call.

I attempted this approach - observing a promise when I console.log the outcome:

testCreditFunction = (id) => {
    let uid = getUserByReferrerId(id).then(doc => { 
        console.log("uid1", doc);    
    });
}

Additionally, I tried this method - with the log indicating null for uid.

testCreditFunction = (id) => {
    let uid = '';
    
    (async () => {
        uid = await getUserByReferrerId(id);
        console.log("uid in the function", uid);
    })();
}

I have noticed similar queries raised multiple times, and despite experimenting with various solutions, none seem to work in my case. It's puzzling as I've successfully implemented the same process elsewhere, leaving me uncertain of what sets this instance apart.

Answer №1

Revise your function with this new code snippet.

const fetchUserByReferrerId = async id => {
  return await firestore
  .collection(FIRESTORE_COLLECTIONS.USERS)
  .where('referralId', '==', id)  
  .get();
}

Here is an alternative approach to retrieve data.

 retrieveUserData = (id) => {

 let queryResult = '';
        
    (async () => {
      queryResult = await fetchUserByReferrerId(id);
      const document = queryResult.docs[0];
      console.log("Retrieved document ID:", document.id);
  })();

Answer №2

Upon initial inspection, I immediately noticed that you are blending async/await and .then/.error, which can lead to confusion. Although not against the rules, this approach can make the code harder to follow.

Just like others have pointed out in the comments, it is essential to include a return statement for the promise to be resolved successfully. Here's a revised version of the getUserByReferrerId function using async/await:

const getUserByReferrerId = async id => {
  const usersRef = firestore.collection('users');
  const query = usersRef.where('grsfId', '==', id);

  const snapshot = await query.get();
  if (snapshot.empty) {
   console.log('no document found');
   return;
  }

  console.log('document found');
  const doc = snapshot.docs[0];
  return doc.id;
}

I've separated the query construction steps from the snapshot request, with only the get operation under a promise. This structure aims to enhance clarity and organization in the code.

To utilize the updated getUserByReferrerID function, simply use await followed by a check to ensure the result is not undefined:

const userID = await getUserByReferrerId('someid')

if (!userID) {
  console.log('user does not exist');
}

console.log(`User ID: ${userID}`);
  

P.S. - I recommend renaming the function to getUserIdByReferrerId to accurately reflect that an ID is being returned instead of a user document. Alternatively, you could return the user object and keep the original name.

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

Sharing Angular 4 components in my project - collaboration at its finest

I have been working on an Angular project that consists of a variety of UI components. I would like to make these components available for use in other Angular projects and share them within the npm community. All of the components are located in a shared ...

Using Angularjs: Trigger Directive Execution Post Completion of ng-init Function

I'm facing an issue with calling a function in ng-init within my HTML file. The function is responsible for making an API call and collecting data, which is then assigned to a scope variable and passed to a directive. Initially, the controller gets e ...

What is the best way to incorporate a PHP variable into my Jquery image slider?

I've been experimenting with a Jquery Image slider and I'm interested in enhancing it further. My goal is to display two divs when the full-size image loads, one containing an image title and the other providing a description of the picture. How ...

Various <a> elements adjust the HTML code based on the selected option

I am working with the following code snippet: <!-- LANGUAGE --> <div class="languages_box"> <span class="red">Languages:</span> <a href="#" class="selected"><img src="../images/au.gif" alt="" title="" border="0" he ...

Expanding and collapsing UI elements within an ngRepeat loop in AngularJS

I have been attempting to incorporate collapsible panels within an ngRepeat loop. Below is the code I have been using: <div class="panel panel-default" ng-repeat="element in elements"> <div class="panel-heading"> ...

Bazel: Utilizing the nodeJS_binary rule for executing "npm run start" - A Guide

Is there a way to utilize the nodejs_binary rule in order to execute a standard npm run start? While I can successfully run a typical node project using this rule, I am struggling to run the start script specified in package.json. Below is what I currently ...

How can attributes be passed to a Vue JS computed property getter and setter?

Attempting to utilize computed properties for binding input fields with the Vuex Store has presented some challenges. Each Data Stream in my application has dynamic input fields, managed through the admin section. I need to allow users to select a specific ...

Turning a SUM / IF query with INNER JOIN in MySQL into a knex query

After successfully creating a MySQL statement for my project, I am now facing the challenge of translating it into a knex.js query builder. Unfortunately, I have not been able to find a straightforward solution in the knex.js documentation as there is no ...

Exploring the World of Three.js: Modifying Facial Structures

Can anyone help me figure out how to obtain the average x, y, z coordinates of a specific face in three.js? Or, could someone guide me on extracting the individual x, y, z coordinates of the three vertices that compose a face and averaging them? Currently ...

"Concurrency issues arise when using multiple AJAX calls in jQuery, causing confusion with

This piece of JavaScript code involves a series of AJAX calls to my FastCGI module in order to retrieve certain values. However, there seems to be an issue where the value intended for display in "div2" is ending up in "div1", and vice versa, ultimately ca ...

The login functionality on Passport.js is not syncing with Angular updates

I'm currently in the process of developing my first full-stack MEAN application, but I've encountered some issues due to following an outdated tutorial with newer npm packages. The particular problem arises when handling the login functionality w ...

Encountering problem when trying to upload several images at once using a single input in CodeIgniter with

I'm attempting to use CodeIgniter and AJAX to upload multiple images using a single input field. Here's the code I have so far: HTML: <input type="file" name="files[]" id="file" multiple /> AJAX: $("#addItems").on("submit",function(e) { ...

Transform the color of links in a Sankey diagram on Google upon clicking a node

Currently, I am in the process of creating a Sankey diagram using Google charts. As of now, I have implemented the following CSS: svg path:hover { fill: red; } However, I have noticed that this code only changes the color of the links when hovering over ...

Take me to a different page through colorbox

Currently, I am facing an issue with my colorbox. My objective is to redirect to another page once a certain value has been validated using PHP. Below is the code snippet that I have attempted: if (isset($_POST['confirm'])) { echo "<scrip ...

JavaScript throws an error because document is not defined

view image description hereWhy am I encountering an error after installing node.js and running various JavaScript commands? It seems like the issue is not with my code, but rather that node.js is failing to establish a connection with the server. view ima ...

Issue with Web API and AJAX: Unable to retrieve resource, server returned status code 400

[HttpPost("Login")] public async Task<IActionResult> Login([FromBody] SigninViewModel formData) { MemberCredential membercredential = await db.MemberCredential.FirstOrDefaultAsync(t => t.MemberAccount.Equals(f ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

Resolution-specific CSS styling

As a newcomer to website development, I have some knowledge of CSS, HTML, and Javascript. However, I am encountering issues with my website. When viewed on low screen resolutions or mobile devices, the right side of my site is cut off, making it impossible ...

What is the best way to create a loop with JSON data?

My challenge is to showcase json data using a loop. I have received the following results, but I am unsure of how to display them with a loop. [ {"latitude":"23.046100780353495","longitude":"72.56860542227514"}, {"latitude":"23.088427701737665"," ...

What steps can be taken to integrate JavaScript into an ASP.NET control?

<script type="text/javascript"> $(document).ready(function () { $('input[name="time"]').ptTimeSelect(); }); </script> the script shown above is functioning correctly with this HTML input: <input name="time" value= ...