Passing asynchronous data from method1 to method2 without impacting the functionality of the script responsible for fetching the asynchronous data in method1

When working with TypeScript, I encountered an issue while trying to invoke an external script called SPCalendarPro within a private method that asynchronously fetches data. The script is invoked in the following manner:

private _getSPCalendarPro() {
  const spcalpro: any = require('./spcalendarpro.js');
}

After invoking the script, I need to call a function as shown below:

spcalpro.getCalendarEvents({
  listName: "StaffSchedule"
}).ready(function(data, obj) {
  if (obj.error) console.error( obj.error );
  console.table( data );
});

The complete method looks like this:

private _getSPCalendarPro() {
  const spcalpro: any = require('./spcalendarpro.js');

  return spcalpro.getCalendarEvents({
    listName: "StaffSchedule"
  }).ready(function(data, obj) {
    if (obj.error) console.error( obj.error );
    console.table( data );
    return obj;
  });
}

This script returns a data and obj variable which must be utilized in another method. However, calling the above method from another function results in receiving the .ready() function as text. Omitting the .ready() part provides me with the fetched object but with empty data. This occurs because the data is fetched asynchronously and not yet resolved when the method is returned. The returned object includes:

listName: async: fields: userEnvData: callback: CamlQuery: data:

The method 'private _calendarData()' where I call the '_getSPCalendarPro' method looks like this:

private _calendarData() {
  const calObj = this._getSPCalendarPro();
  const calObjData = calObj['data'];
  console.log(calObj);
  console.log(calObjData);
}

Although 'calObj' contains the expected data, 'calObjData' remains undefined. I've attempted using async/await and jQuery deferred, but have had no success. Unfortunately, I could not find a solution for this specific issue. Any assistance would be greatly appreciated.

Thank you.

EDIT I tried to create a promise for '_getSPCalendarPro', but I'm unsure of the correct way to do this since the external script handles the actual data fetching.

private _getSPCalendarPro(): Promise<void> {
  const spcalpro: any = require('./spcalendarpro.js');

  const spcal = spcalpro.getCalendarEvents({
    listName: "StaffSchedule"
  }).ready(function(data, obj) {
    if (obj.error) console.error( obj.error );
    console.table( data );
    return obj;
  });

  return spcal().then((response) => {
    return response;
  })

}

FINAL WORKING CODE Special thanks to Yoshi.

export interface ISPCalendarPro {
  data: any;
}

private _getSPCalendarPro(): Promise<ISPCalendarPro> {
  const spcalpro: any = require('./spcalendarpro.js');


  return new Promise((resolve, reject) => {
    const spcal = spcalpro.getCalendarEvents({
      listName: "StaffSchedule"
    }).ready(function(data, obj) {
      obj.error
      ? reject(obj.error) // reject on error
      : resolve(obj);    // or resolve
    })
  })
}

private _calendarData() {
  this._getSPCalendarPro().then((calData) => {
    console.log(calData);
  });
}

Answer №1

One possible solution is to utilize a promise and resolve it by utilizing the ready callback that is provided.

Here is an example:

type Info = unknown; // This needs to be defined.

class SomeClass
{
  private _fetchData(): Promise<Info> {
    const dataFetcher: any = require('./dataFetcher.js');

    // Return a promise
    return new Promise((resolve, reject) => {
      // Ready callback
      dataFetcher.fetch({infoType: "CustomerInfo"}).ready(function(infoData, obj) {
        obj.error
          ? reject(obj.error) // Reject on error
          : resolve(infoData);    // Resolve if no errors
      });
    });
  }

  private async _retrieveData() {
    try {
      // Wait for the promise to complete
      const information = await this._fetchData();
    }
    catch (error) {
      console.error(error);
    }
  }
}

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

Transform a text node into an HTML element with the help of JQuery

Consider this HTML snippet: <div> Lorem ipsum <span>dolor sit</span> amet <span>consectetur adipiscing elit</span> eiusmod tempor </div> To select the text nodes [Lorem ipsum, amet, eiusmod tempor], ...

filter failing to provide output

Issue with fetching partnername from the filter function, always returning undefined. administrationList = [ { "runid": 6, "partnerid": 2, "partnername": "test admin2", }, { "runid& ...

Tips for generating a node for the activator attribute within Vuetify?

Vuetify offers the 'activator' prop in multiple components like 'v-menu' and 'v-dialog', but there is limited information on how to create a node for it to function correctly. The documentation states: Designate a custom act ...

Navigate through an overflowing element in react/next

I have a component with a fixed width and overflow-x-auto. I want to hide the scroll bar and replace it with arrow buttons for scrolling left and right. How can I add this functionality to my component? Here is the code for my component: <div className ...

What is the process for obtaining jsonencode data in a Laravel application?

server control public function room_details(Request $request) { $data['room_number'] = $request->id; $data['result_set'] = Rooms::find($request->id); echo $data['result_set']; return view('room ...

Add a fresh item to a list using jQuery

Attempting to add a new list item using jQuery. In this scenario, the process works well, but when attempting to retrieve the value of an input field using .val(), no list item is created. http://www.example.com Code snippet: $(document).ready(functi ...

Process JSON data from an input using Javascript

I am encountering an obstacle at the final step of my data flow process. Currently, I am in the midst of developing an application that retrieves input from an HTML form field and utilizes Ajax to fetch data relevant to the user's input. Allow me to e ...

What steps should I take to export a function from a React functional component in order to create a reusable library?

Currently, I am in the midst of developing a React component library and one of my components contains a function that I want to export. The purpose of the addParticle function is to enable users of the library to dynamically insert particles into a cont ...

How can I insert my JavaScript functions into the JSF event queue for processing?

Is there a way to tap into the default JSF ajax(JS) event queuing system in order to execute events sequentially? I am attempting to align my JS events with this queue. Is there a global variable that can facilitate this synchronization? ...

The Material UI Icon rendered using document.createElementNS in React is failing to load properly

I'm currently developing a tags section for my app, similar to the tags feature in a new Stack Overflow question form. For this, I am utilizing the Material UI close icon. You can see how it is implemented in this tutorial on YouTube. (I have confirme ...

The useStarRating() hook continues to display 0 even after the user has interacted with the star component

I've created a custom useStarRating hook to manage the state of a star rating component in my React project. Everything seems to be working properly, but I'm facing an issue with retrieving the updated value of currentValue after the user interac ...

Choosing items by pressing "shift + up arrow"

I have a collection of elements, each representing one line of text. When you click on an element, it changes color. If you then hold down "shift + arrow up," the items above it are also selected. How can this functionality be implemented? My initial app ...

Is it possible to continuously increase the value of a CSS property with each click?

I am trying to implement a feature where the value of an element decreases each time a different element is clicked. Currently, I have the following code: $("#trigger_heritage").click(function () { $(".heritage_content ul").css("margin-left", + -880); ...

Executing Code from Tab only upon tab activation

I have multiple tabs on my page, and I want to have one tab with a widget that only loads when the user clicks on it, instead of loading along with all other tabs when the page loads. <div class="tabbable tabbable-custom"> <ul class="nav nav-t ...

Tips for dynamically expanding the interface or type of an object in TypeScript

Currently, I am exploring the integration of PayPal's Glamorous CSS-in-JS library into a boilerplate project that also utilizes TypeScript. Glamorous provides a way to incorporate props into an element as shown below: const Section = glamorous.secti ...

ng-show and ng-hide toggling for the active row

I have a single table where I am implementing row hide and show functionality using Angular for editing and saving purposes. So far, everything works as expected. $scope.init=function(){ $scope.editable=true; } Now, when I click on the edit button ...

Unable to trap error using try-catch block within an asynchronous function

I'm attempting to integrate a try-catch block into an async function, but I am having trouble catching errors with status code 400 using the code below. const run = async () => { const response = await client.lists.addListMember(listId, { ema ...

The fade effect in React and material ui is consistent across both elements

I am facing an issue with a list where, for each list sibling onclick, a different element fades in with different text. The problem occurs when the fade effect starts once on siblings in the list and then disappears, not enabling again. This is the code: ...

Update the document by sending the data and making changes based on the AJAX response

Currently, I am avoiding using jQuery and trying to work with the following code in PHP: <?php header ( 'Content-Type: text/xml; charset=utf-8' ); $con = @mysql_connect ( "localhost", "root", "" ) or die ( "Couldn't connect to database" ...

Extracting and retrieving the value from the paramMap in Angular/JavaScript

How can we extract only the value from the router param map? Currently, the output is: authkey:af408c30-d212-4efe-933d-54606709fa32 I am interested in obtaining just the random "af408c30-d212-4efe-933d-54606709fa32" without the key "authke ...