【发布时间】:2020-01-03 09:15:51
【问题描述】:
您好,我有以下问题:
我在按下按钮时对服务器执行两个async 请求。
第一个async 调用实际上是对提交表单的javascript 本地方法的调用。
第二个async 调用是使用服务的post。
我不明白为什么第二个请求有时会在第一个请求之前发生:
declare function submit(id: string): any;
@Component({
selector: 'index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
public viewComputers: Computer[] = null;
public catalog: Catalog = null;
constructor(private service: AnubisService) { }
async refreshListAsync() {
this.catalog = await this.service.getCatalogAsync(); //post call to a server
this.viewComputers = this.catalog.computers.items;
}
async cbSubmitAsync() {
var result = this.submit("clientForm"); --call to js submit form method
await this.refreshListAsync(); //how can this happen before the first call
}
}
Javascript 调用
function submit(id) {
return new Promise((resolve, reject) => {
var form = document.getElementById(id);
form.onerror = () => {
reject("could not post");
}
var xhr = new XMLHttpRequest();
var action = form.getAttribute('action');
var method = form.getAttribute('method');
xhr.open(method, action);
xhr.onload = function () {
if (xhr.status == 200) {
resolve(xhr.response);
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
var data = new FormData(form);
xhr.send(data);
});
}
服务后调用
public async getCatalogAsync():Promise<Catalog>{
let route=this.BaseUrl+"/api/admin/get-catalog";
try {
var data=await this.http.get<Catalog>(route).toPromise<Catalog>();
return data;
}catch(ex){
return null;
}
}
我的问题是:在cbSubmitAsync 方法中,第二次调用如何在第一次调用之前发生,如果是这样,我如何将它包装在一个承诺中(我也尝试过等待submit,但无济于事)
【问题讨论】:
-
您告诉过(我也尝试过等待提交但无济于事)这是什么意思?你的意思是
var result = await this.submit("clientForm");在cbSubmitAsync方法中。如果是这样,我相信它应该有效 -
我试过
submit和await submit -
它应该只添加 await 就可以工作。我尝试了这个场景,它对我来说非常好,所以你能用你的问题创建 JSFiddle
标签: typescript asynchronous post promise xmlhttprequest