TS代码:
var APIres: any;
export class Component implements OnInit {
async getInfo(){
await this.apicall();
console.log('API response', APIres)
}
async apicall(){
var request = new XMLHttpRequest();
request.open('POST', 'URL', true);
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'Bearer ' + accessToken);
request.onreadystatechange = async function () {
console.log('Got Values')
await res(JSON.parse(this.responseText));
}
request.send(content);
}
}
async function res(x){console.log('out');APIres = x} //Outside of export
输出:
API response undefined
Got Values
out
期望输出:
Got Values
out
API response res
2条答案
按热度按时间cdmah0mi1#
代码中没有任何内容将XHR调用的完成与
apicall
返回的承诺联系起来,尽管您 * 可以 * wrap XHR in a promise,但使用现代的替代品fetch
更有意义。另外,正如VLAZ在评论中指出的,作为方法调用的副作用填充全局数据是一种糟糕的做法,相反,让方法 * 返回 * 必要的数据。
下面是使用
fetch
的示例:34gzjxbg2#
添加
async
不会神奇地导致函数等待事件用承诺来 Package 你的功能