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

Ways to incorporate sass:math into your vue.config.js file

While using vue-cli with Vue 2.6 and sass 1.49, I encountered errors in the console related to simple division calculations: Deprecation Warning: Using / for division outside of calc() is deprecated and will be removed in Dart Sass 2.0.0. I attempted to ...

Adding a property conditionally in jsx: A guide

I have a simple example of Material UI RadioGroup code that I want to display conditionally in either a row or column format. By default, it is displayed in column format. Below is the code snippet: <RadioGroup aria-label="gender" name=&q ...

Tips for activating the default 500 error page in Next.js

I'm having trouble getting Next.js to display its default 500 error page. While most sources discuss creating a custom error page, the Next.js documentation only briefly references their built-in 500 error page. I want the default page to show up when ...

What is the reasoning behind CoffeeScript automatically adding a function when extending an Object?

I'm currently working on a helper method to identify the intersection of two hashes/Objects in this manner... Object::intersect = (obj)-> t = {} t[k] = @[k] for k of obj t x = { a: 1, b: 2, c: 3 } w = { a: true, b: 3 } x.intersect(w) #=> ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Animating a Bootstrap 4 card to the center of the screen

I am attempting to achieve the following effect: Display a grid of bootstrap 4 cards Upon clicking a button within a card, animate it by rotating 180 degrees, adjusting its height/width from 400px - 350px to the entire screen, and positioning it at the c ...

Obtain a masterpiece by creating a canvas in React

Greetings! I have developed a drawing app using react and I am looking for a way to capture what the user has drawn on the canvas when they release the mouse button. This process should repeat continuously until the user stops drawing. Can anyone suggest h ...

Heroku hosting a React/Node application that serves up index.html and index.js files, with a server actively running

It seems like the issue I'm facing is related to my start scripts. After researching online, I've come across various start scripts shared by different people. Some suggest using "start": "node index.js" -> (this doesn't start my server and ...

Storing Firestore Timestamp as a Map in the database

Snippet Below const start = new Date(this.date + 'T' + this.time); console.log(start); // Thu Sep 12 2019 04:00:00 GMT+0200 const tournament:Tournament = { start: firebase.firestore.Timestamp.fromDate(start) } When passing the tournament ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

Determine whether there are a minimum of two elements in the array that are larger than zero - JavaScript/Typescript

Looking for an efficient way to determine if there are at least two values greater than 0 in an array and return true? Otherwise, return false. Here's a hypothetical but incorrect attempt using the example: const x = [9, 1, 0]; const y = [0, 0, 0]; c ...

How can jQuery help me load a lengthy webpage with various backgrounds that change according to the vertical scroll value?

I have been given a design that is 960px wide and approximately 7000px tall, divided into five segments stacked vertically at random points. There is a fixed sidebar that scrolls to each segment when a navigation link is clicked. The layout includes slider ...

Encountering a "focus" error with React-Native-Phone-Input library, where the property is null

For my project, I decided to incorporate the react-native-phone-input library. Everything was going smoothly until I encountered an issue with their focus function. Initially, it worked perfectly fine, but subsequently, when I attempted to input a phone nu ...

Retrieve JSON data from a server using jQuery following the submission of a form

Similar Question: JQuery Ajax Return value After filling out a login/register form, the server sends me to a JSON page. I am trying to retrieve that JSON data into a JavaScript/jQuery file without being redirected to that page. Is there a way to acce ...

The React server-side rendering isn't reflecting changes made on the client-side route

Upon the first refresh, both the server and client side are updated; however, subsequent updates only affect the client side when switching pages with react router. For instance, refreshing the page or entering a new URL causes changes on the server and t ...

Leveraging MVC 4 for Web Service Development

I am currently in the process of developing a web service using MVC 4 and HTML for the client interface. One issue I am facing is that my HTML file is located outside of the application, while my MVC service is running on Visual Studio IIS Express. I' ...

What is the best way to use jQuery to insert this block of HTML into a page from a JSON response?

<script type="text/javascript"> var dataString2 = 'run=captchagood&comment=' + comment; $.ajax({ type: "POST", url: "process.php", data: dataString2, dataType: "json", error: 'error', success: function ...

Managing changes to object properties in Angular

I am encountering a situation where I have an object containing both an 'id' and 'name' property, structured like this: function format(id){ return '(' + id + ')'; } function MyObject(id){ this.id = id; this. ...

Having trouble establishing a connection to the server through curl

Whenever I attempt to send a request to the server on localhost, I keep getting this error message: Error: call to URL failed with status 200, response {"resultCode":503,"resultMessage":"Yakeen Failure: The ID Is Not Found at NIC","referenceNum ...

The Jquery flot plugin is failing to plot the graph accurately based on the specified date

I am currently working on plotting a graph using the jquery flot plugin with JSON data. Here is what I need to do: Upon page load, make an AJAX call to receive JSON data from the server. From the received JSON, add 'x' and & ...