I have the following code and as I havent worked with Promises a lot, then I am trying to understand, this question is more about an easy way to understand the code and not about a specific problem:
private getRequestDigest(siteUrl: string): Promise<string> {
const component: Reactwithmsgraphandsharepoint = this;
return new Promise<string>((resolve, reject): void => {
component.request(`${siteUrl}/_api/contextinfo`, 'POST').then((data: { FormDigestValue: string }): void => {
resolve(data.FormDigestValue);
}, (error: any): void => {
reject(error);
});
});
}
private request<T>(url: string, method: string = 'GET', headers: any = null, data: any = null): Promise<T> {
return new Promise<T>((resolve, reject): void => {
const xhr: XMLHttpRequest = new XMLHttpRequest();
xhr.onreadystatechange = function (): void {
if (this.readyState === 4) {
if (this.status === 200) {
resolve(this.response as T);
}
else if (this.status >= 400) {
reject({
message: this.response['odata.error'].message.value,
statusText: this.statusText,
status: this.status
});
}
}
};
xhr.open(method, url, true);
if (headers === null) {
xhr.setRequestHeader('Accept', 'application/json;odata=nometadata');
}
else {
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, headers[header]);
}
}
}
xhr.responseType = 'json';
xhr.send(data);
});
}
On the get request method, the request method is executed, but with 2 parameters, but the signature receives more, how does it know which parameters? by argument order?, doesnt it need all arguments to be passed?
What is resolve and reject?
I understand than code in then is executed after the web request is executed, however in the then I dont see a function at all, I see data: { FormDigestValue: string }): void => which is a syntax I dont understand.
What is resolve(this.response as T); ? I come from C# and generics, so it looks like it can return anything?
And finally, can I put anything on a reject?
reject({ message: this.response['odata.error'].message.value, statusText: this.statusText, status: this.status });