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);
});
}