如何解决如何等待HTTP请求的结果同步的HTTP请求,HTTP请求作为Promise
我有一个打字稿服务,该服务通过来自服务器的htpp请求加载基本数据。对于几种数据,有几种要求,从不依赖的数据到依赖于数据的数据按顺序排列,为此开始加载。因为不能保证异步http请求,所以按请求(例如下面的示例中的客户)的数据加载已完成,因此请尽力开始加载依赖于该请求的数据(例如下面的示例中的设备),我无法参考向已加载的客户加载设备。但是我想,在加载引用(客户)的数据完成后,开始对依赖数据(设备)进行整理。我想我需要使用Promise,但是如何在以下代码情况下实现具体呢?
export class BaseDataService
{
customers: Customer[] = new Array();
devices: Device[] = new Array();
// Loads the base data arranged in order from undependent data to data dependent data
loadBaseData() {
this.loadCustomers();
// this operation should be started after loading customers has finished (the response json
//is parsed to an array of customers at set to the instance variable of this service class)
this.loadDevices();
}
// Loads the customers and adds them to the collection of customers.
// Also puts the response json string of the customers to the local storage.
loadCustomers() {
console.log("Load customers");
var requestURL = 'https://myurl/kunden_json_user_extern.php';
var auth = window.localStorage.getItem('auth');
var requestparam = "auth="+auth;
var request = new XMLHttpRequest();
request.open('POST',requestURL);
request.setRequestHeader("content-type","application/x-www-form-urlencoded");
request.send(requestparam);
request.onload = () => {
if (request.status === 200){
console.log("Load customers response");
// gets as json string with the customers array
var response = request.response;
// parses the json string of customers to an array of customers objects
this.customers = this.parseCustomers(response);
console.log("Load customers complete");
}
else if (request.status === 401){
alert("unautorized");
}
else {
// lade saved items aus local storage
alert("unerwarteter Fehler");
}
}
}
// Loads the devices and adds them to the collection of devices.
// Also puts the response json string of the devices to the local storage.
loadDevices() {
console.log("Load devices");
var requestURL = 'https://myurl/geraete_json_user_extern.php';
var auth = window.localStorage.getItem('auth');
var requestparam = "auth="+auth;
var request = new XMLHttpRequest();
request.open('POST',requestURL);
request.setRequestHeader("content-type","application/x-www-form-urlencoded");
request.send(requestparam);
request.onload = () => {
if (request.status === 200){
console.log("Load devices response");
var response = request.response;
window.localStorage.setItem('devicesresponse',response);
this.devices = this.parseDevices(response);
console.log("Load devices complete");
}
else if (request.status === 401){
alert("unautorized");
}
else {
// lade saved items aus local storage
alert("unerwarteter Fehler");
}
}
}
// Parses a json string formatted like the response of customers to an array of customers
parseCustomers(customersjson: string)
{
let customerarray = JSON.parse(customersjson);
let customers: Customer[] = [];
for (let i = 0; i < customerarray.length; i++) {
let customer: Customer = new Customer();
customer.setId(customerarray[i]['id']);
customer.setName(customerarray[i]['name']);
customer.setPlace(customerarray[i]['ort']);
customer.setStreet(customerarray[i]['strasse']);
customers[i] = customer;
}
return customers;
}
// Parses a json string formatted like the response of devices to an array of devices
parseDevices(devicesjson: string)
{
let devicearray = JSON.parse(devicesjson);
let devices: Device[] = [];
for (let i = 0; i < devicearray.length; i++) {
let device = new Device();
device.setId(devicearray[i]['geraet_id']);
device.setSerialnumber(devicearray[i]['geraet_seriennummer']);
device.setDescription(devicearray[i]['geraet_bezeichnung']);
// here i would like to refer to a prevoiusly loaded customer
//device.setCustomer(this.baseDataService.getCustomer(devicearray[i]['geraet_kunde_id']);
device.setLocation(devicearray[i]['geraet_standort']);
devices[i] = device;
}
return devices;
}
}
解决方法
您可以将回调传递给任何“加载”功能,因此:
此代码:
loadBaseData() {
this.loadCustomers();
// this operation should be started after loading customers has finished (the response json
//is parsed to an array of customers at set to the instance variable of this service class)
this.loadDevices();
}
更改为以下代码:
loadBaseData() {
this.loadCustomers(() => {
this.loadDevices();
});
}
然后在您的request.onload
中调用此回调:
// Loads the customers and adds them to the collection of customers.
// Also puts the response json string of the customers to the local storage.
loadCustomers(callback) { // <--- this is a callback passed to function
// ... many code here ...
request.onload = () => {
// ... many code here ...
console.log("Load customers complete");
if (typeof callback === 'function') callback(); // <--- here we call it
}
// ... many code here ...
,
您可以像下面这样进行synchronous ajax
呼叫。因此,它在执行下一条语句之前等待响应。
xhr.open("POST",url,false);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。