Improper return of object instead of value by async function

When I call an async function, my expectation is to receive a JSON payload that will allow me to extract a specific value from the object. However, all I get in return from the function is [object Object]

This async function was initially called within a normal function, so I attempted changing the parent function to async as well. This adjustment proved to be beneficial as it originally resulted in only receiving a value of [object Promise]

The initial attempt looked like this:

const sendRequestToApprover = (userId, announcement, username) => {
  const { title, details, channel } = announcement;

  const channelName = channels.getChannelName(channel);
  console.log('channelName' + channelName);

and the getChannelName function appears as follows:

async function getChannelName(id) { 
  try {
    return await api.get('/channels.info', {
      params: { 
        token: botToken,
        channel: id,
      }
    });
  } catch (err) {
    console.log(err);
  }
}

To resolve the issue of getting [object Promise], I made the following modification to sendRequestToApprover:

async function sendRequestToApprover(userId, announcement, username) {
  const { title, details, channel } = announcement;

  const channelName = await channels.getChannelName(channel);

  console.log('channelName' + channelName);

It's important to note that the function is now async and I included await in the function call.

I'm aware that the expected payload will resemble the following structure:

{
    "ok": true,
    "channel": {
        "id": "CJSFDR83T",
        "name": "general",
...
}

Despite knowing the expected format of the payload, I'm unable to access the name property in this particular case. I've successfully achieved this in other functions, but for some reason, this one has left me scratching my head. The variable channelName continues to display [object Object].

Answer №1

If you find yourself in this scenario:

console.log("channelName" + channelName);

You are invoking the toString function on channelName, which, when applied to an object, yields [object Object].

console.log("Object.toString() -> " + { foo: "bar" });

To prevent this, consider passing an additional argument to console.log.

console.log("Object.toString() -> ", { foo: "bar" });

Answer №2

After spending the weekend grappling with this issue, I finally managed to make a breakthrough.

The solution came to me when I decided to assign the API call to a variable and log the result.

try {
    const result = await api.get('/channels.info', {
      params: { 
        token: botToken,
        channel: id,
      }
    });

Upon logging result, I was able to see the payload! This led me to update the function in the following manner:

async function getChannelName(id) { 
  try {
    const result = await api.get('/channels.info', {
      params: { 
        token: botToken,
        channel: id,
      }
    });
    return result.data.channel.name
  } catch (err) {
    console.log(err);
  }
}

Now, my channelName variable successfully retrieves the channel 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

Implementing a hamburger menu and social media sharing buttons on websites

Currently working on my personal website and delving into the world of Web Development, I have some inquiries for seasoned developers. My first query revolves around incorporating a hamburger menu onto my site for easy navigation to other pages. After att ...

Check the box to track the current status of each individual row

Recently, I encountered an issue with a form containing dynamic rows. Upon fetching records, my goal was to update the status of selected rows using checkboxes. Although I managed to retrieve checkbox values and dynamic row IDs successfully in the console ...

Leverage jQuery UI to execute methods with identical names across distinct widgets

Let's say I've made a bunch of different widgets (mywidget1, mywidget2, ...) and they all have a method called doSomething. To call this method, I can use: $("#elem").widget1("doSomething"); However, this method requires me to know the spec ...

"Exploring the differences between a singular object holding an array of objects versus a straightforward array

In my Nodejs project, I have a complex object that contains an array of objects (obtained from an API request) and a simple array of values. Here is how they are structured : // Object > Array > Objects (result of an API request) : { "data& ...

jquery method for retrieving default value from dropdown list

When no option is selected from the dropdown list, I require the default value to be used for business logic purposes. ...

Go through the information within each row of the table

My data table is structured to display user information in each row, utilizing the userDetails array. The issue I'm facing is that instead of fetching one piece of data per row while iterating through tableData, all the information for each row is bei ...

Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here. Service (Mock): import { Injectable } from '@angular/core'; import { ERGEBNISSE } from "./mock-ergebnisse"; @Inject ...

Set up a global configuration for all $.ajax calls to enable automatic retries in case of a timeout

Looking for a solution to implement a global timeout function using $.ajaxSetup in my Phonegap app. The goal is to automatically retry ajax GET or POST requests in case of timeout, specifically due to poor internet connection. As a Backbone.js user, I hav ...

Determine whether any element in the array matches a property of the object

Let's start with an array: arr=[ "EMPRESA", "CD_DIRECAO", "DT_INI_DIRECAO" ] Next, we have an object: primary = { "EMPRESA": {"type": "varchar"}, "CD_DIRECAO": {"type": "varchar"}, "DT_INI_DIR ...

Is there a way to simplify my code and improve readability without sacrificing performance?

After completing the development of an explosive hoverboard model, it is now live on my website: . However, the code I've written seems to be quite messy and I'm struggling to optimize it without compromising performance. Is there a way to effici ...

Mastering the correct usage of Express middleware functions in routers

Displayed in this instance, are the csrfProtection and parseForm functions being utilized as parameters/callbacks within the GET and POST requests... var cookieParser = require('cookie-parser') var csrf = require('csurf') var bodyParse ...

Is it possible to use JavaScript to scrape content from another website and incorporate it into my HTML document?

Attempting to web scrape another website in order to display its content on my own site. I have written JavaScript code that works, but only when triggered on the website's onClick event. var button = document.getElementById("scrape-website"); button ...

Using JavaScript to create an array from information retrieved from an AJAX

Encountering difficulties in retrieving data from an AJAX file, I am attempting to modify the data source of a web application originally defined in JavaScript as: var ds = [ 'Sarah', 'John', 'Jack', 'Don', 'B ...

What is the best way to execute a function after a successful Stripe payment in an Angular application

For my project, I need to integrate the Stripe payment gateway. I am looking for assistance in calling the API function "orderStatusUpdate" after a successful payment by the customer. Can anyone help me with this? loadStripe() { if(!window.document. ...

What is the best way to adjust the size of a button using CSS within a ReactJS

I am facing an issue where I need to create a button with a specific width, but the template I'm using already has predefined styles for buttons. When I try to customize the button's style, nothing seems to change. Below is the code snippet: Her ...

Textures have been added by the user in the three.js platform

Click here to access the jsFiddle adaptation of this problem. In my quest to develop a cutting-edge 3D web application, I aim to allow users to choose an image file from their device: <input id="userImage" type="file"/> Once a file is selected, th ...

Check if the content key Json exists by implementing Vue

Can anyone help me with checking the existence of "novalue"? For instance: { name: "maria", city_id: "novalue" .... } What would be the best way to do this in Vue? Should I use <div v-if="condition"> or a function? ...

Utilize drag and drop functionality to interact with an HTML object element

I am struggling with a div that contains a PDF object and draggable text: <html> <head> <script> function allowDrop(ev) { ev.preventDefault(); } function drop(ev) { alert("DROP"); } </script> </head> <body> <di ...

Tips for creating a consistent header and footer across an HTML CSS web application

My previous projects involved using ASP.NET MVC and utilizing @Html.Partial("_header") to incorporate common static HTML across different pages. However, my current project is a pure HTML CSS and JS web app with no server-side technology. The la ...

Is there a way to automatically focus on a newly created element using JavaScript?

Whenever a user presses the enter key in a single input field, it will become disabled and a new one will appear. I am looking to automatically focus on the newly created input field each time, while also removing the default blue border that appears when ...