Building upon the preceding inquiry, a ReferenceError has occurred due to the object being undefined

After researching online, I came across a similar question marked as a duplicate that brought me to this link: How do I return the response from an asynchronous call?.

Even though I couldn't find a solution in that thread, it seems like I may need to resort to AJAX for returning this object. Since my functions and GET Request haven't completed, I have a new query on how to adapt this for asynchronous return. While I grasp the concept of Promises and async/await, I'm still uncertain about implementing them in order to access the object globally.

[Original Question]

I am currently trying to return an object within the below function but keep encountering the error message

ReferenceError: object is not defined
. My objective is to be able to access this object globally, however, the scope seems to prevent me from doing so. Am I missing something crucial here?

Whenever I attempt to set a global variable, it doesn't get updated accordingly.

For instance, when I define var globalObject = {}; outside and then assign globalObject = object inside the object, it fails to modify the variable {}

function getTicket (ticketID) {

  var urlID = contentID;

  var request = require("request");

  var options = {
    method: 'GET',
    url: `https://www.mywebsite.com/api/${urlID}/body.json`,
    headers: {'content-type': 'application/json', authorization: 'Basic PASSWORD=='}
  };

  request(options, function (response, body) {


    var obj = JSON.parse(JSON.stringify(body));
    var objContent = JSON.parse(obj.body);

    var object = {
      id: urlID,
      url: 'https://www.mywebsite.com/api/' + urlID,
      value: objContent
    };

    console.log(object.id);
    console.log(object.url);
    console.log(objContent.body[0].body);

  });
return object;
}

getTicket(380289);

Answer №1

To make your function return a promise, you can then use the await keyword when calling it:

function fetchTicket(ticketID) {
  var urlID = contentID;

  var request = require('request');

  var options = {
    method: 'GET',
    url: `https://www.mywebsite.com/api/${urlID}/body.json`,
    headers: { 'content-type': 'application/json', authorization: 'Basic PASSWORD==' }
  };

  return new Promise(resolve => {
    request(options, function(response, body) {
      var obj = JSON.parse(JSON.stringify(body));
      var objContent = JSON.parse(obj.body);

      var object = {
        id: urlID,
        url: 'https://www.mywebsite.com/api/' + urlID,
        value: objContent
      };

      console.log(object.id);
      console.log(object.url);
      console.log(objContent.body[0].body);
      resolve(object);
    });
  });
}

await fetchTicket(380289);

Remember to ensure that your call is made within an async block. If you are in the global scope, you can do this:

(async function() {
  await fetchTicket(380289);
})();

For more information on using await in the global scope without async keyword, check out this Stack Overflow post.

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

Python can be used to display the converted JSON value as output

Trying to convert input into JSON using Python: { name: (john, doe) game: "Football" type: athlete }, { name: (lisa, smith) game: "Basketball" type: athlete } Code snippet: import json import os user_input = ...

What's the best way to extract the refresh_token from this JSON in Java/Android programming?

Hello, I need assistance with extracting the refresh_token from this JSON data. Can anyone help me with that? {"scope":"https://api.paypal.com/v1/vault/credit-card https://uri.paypal.com/services/payments/futurepayments https://uri.paypal.com/services/i ...

Discovering documents using the outcome of a function in mongoose

Hey there, I have a scenario with two schemas known as user and driver, both containing latitude and longitude attributes. My goal is to search the database for nearby drivers based on the user's current location (latitude and longitude) using a custo ...

Exploring the depths of a nested dictionary by accessing paths and values through recursive methods

Is there a way in Python 2.7 to dynamically access and display the keys and values of a nested dictionary? For example, consider this nonsensical scenario: Typically, one might use the following approach: import json json_sample = 'sample_dict.json ...

Implementing file uploads with Bootstrap, jQuery, and Laravel

Looking to incorporate the blueimp jquery file upload feature into my Laravel app. Check it out here: https://github.com/blueimp/jQuery-File-Upload The form is set up and working properly with the plugin, but facing issues with creating server-side script ...

Ensure the accuracy of submitted form information

I am seeking to enhance the validation process for my form, which is already using jquery.validate.min.js for validation. I want to incorporate another layer of validation by making an ajax call to my MySQL database to check if the email address provided i ...

Attempting to retrieve information from my MongoDB database and populate it into a <table> structure on a web page

My objective is to extract data from a MongoDB database and display it in an HTML table. Specifically, I am trying to retrieve information from the hangman database's players collection, which contains fields for name and score. Can anyone help me ide ...

How to use the sha512 hash function in Node.js for Angular2 and Ionic2 applications

I'm attempting to generate a SHA512 Hash in Angular2 (Ionic2) that matches the PHP function hash('sha512'). After trying out different modules like crypto-js, crypto, and js-sha512, I keep getting a different Hash compared to PHP. I even a ...

Creating a static Top Bar that remains unaffected by page refreshing using Ajax or any other method can be achieved by implementing JavaScript and CSS

I've designed a sleek top bar for my upcoming website project. Below is the CSS code snippet for creating this clean div bar: .topbar { display:block; width:100%; height:40px; background-color:#f5f5f5; } I'm looking to incorporate a simple .SWF ...

Successfully updating a document with Mongoose findByIdAndUpdate results in an error being returned

findByIdAndUpdate() function in my code successfully updates a document, but unexpectedly returns an error that I am having trouble understanding. Below is the schema that I am working with: const userSchema = mongoose.Schema({ phone: String, pas ...

What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object. Object: export const urlStrings: { [key: string]: string } = ...

Issue with Javascript Date and Time Validation

My application includes code that is supposed to display HTML pages based on today's date and the time of day (morning, afternoon, or evening). However, it seems like there is an issue with how the time is being checked. Currently, at 2:53pm, only the ...

Is it possible for Python JSON to encode/decode functions from text files?

Is JSON capable of encoding and decoding functions to and from files, in addition to complex data? ...

Button functions properly after the second click

import { Input, Box, Text, Divider, Button } from '@chakra-ui/react'; import { useState } from 'react'; export default function GithubSearchApp() { const [username, setUsername] = useState(''); const [data, setData] = use ...

Utilizing a Single Variable Across Multiple Middlewares in nodeJS

I encountered an issue where I am attempting to utilize one variable across two middlewares, but it displays an error stating that the variable is not defined. Here is an example of my situation: //1st middleware app.use((req, res, next) =>{ cont ...

A helpful guide on integrating a Google font into your Next.js project using Tailwind CSS locally

I'm planning to use the "Work Sans" Font available on Google Fonts for a website I'm working on. After downloading the "WorkSans-Black.ttf" file, I created a subfolder named "fonts" within the "public" folder and placed the font file in there. Be ...

Is there a way to alter the text color using JavaScript on the client side?

Is there a way to change the color of a list item in a ul based on whether it is a palindrome or not? Here is the JavaScript file I am working with: function isPalindrome(text){ return text == text.split('').reverse().join(''); } c ...

"Although the ajax request was successful, the post data did not transfer to the other

i am working with a simple piece of code: var addUser = "simply"; $.ajax({ type: 'POST', url: 'userControl.php', data: {addUser: addUser}, success: function(response){ alert("success"); } }); on the page use ...

Convert data to Excel using PHPExcel, Codeigniter, and Ajax

I am trying to export data as an xls file using PHPExcel in combination with Codeigniter and AJAX. However, I am running into issues where the file is not being generated. Can someone please help me with this? Here is the HTML code for the button: <bu ...

Developing a real-time form that syncs with a MYSQL database for automatic updates

I am currently working on developing a form with multiple drop-down menus. The first dropdown is populated with 'Customer Name' data retrieved from my MYSQL database. Upon selection, the second dropdown menu below it should display the available ...