我有以下代码,因为我没有与Promises一起工作了很多,然后我试图理解,这个问题更多的是一个简单的方法来理解代码而不是一个特定的问题:了解一些Promises代码和打字稿
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);
});
}
在GET请求方法,请求方法执行,但有两个参数,但是签名得到更多的,它是如何知道哪些参数?通过参数顺序吗?,它不需要所有参数传递?
什么是解析和拒绝?我知道,然后执行Web请求后执行,然后在我没有看到一个函数,我看到的数据:{FormDigestValue:字符串}):void =>这是一个语法我不明白。
什么是解析(this.response as T); ?我来自C#和泛型,看起来它可以返回任何东西?
最后,我可以把任何东西放在拒绝?
拒绝({ 消息:this.response [ 'odata.error'] message.value, 状态文本:this.statusText, 状态:this.status });
1 - 参数方法,标题和数据具有默认值,所以如果您不提供它们,则使用默认值。 2 - 解决,拒绝是你用来解决或拒绝承诺的回调函数,3 - =>是一个箭头函数,4 - 解析是一个Promise概念,5 - 是的,你可以拒绝任何你喜欢的东西 –
避免[ 'getRequestDigest'中的'Promise' constructor antipattern](http://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi