简体   繁体   English

如何等待 http 请求的结果(同步 http 请求,http 请求作为承诺)

[英]how to wait for a result of a http request (syncronous http request, http request as promise)

I have a typescript service that loads base data by htpp requests from a server.我有一个 typescript 服务,它通过来自服务器的 htpp 请求加载基本数据。 There are several requests for several data, arranged in order from undependent data to data depending on data, for which loading ist started bevor.有多个数据的请求,按照从不依赖数据到依赖数据的顺序排列,首先开始加载。 Because the asynchronous http requests it is not guaranteed, that loading data by a request (eg customers in the following example) has finished, bevor loading the data that depends on it starts (eg devices in the following example) and i can not refer on loading devices to loaded customers.因为异步 http 请求它不能保证,通过请求加载数据(例如以下示例中的客户)已完成,在加载依赖于它的数据开始之前(例如以下示例中的设备),我无法参考装载设备给装载的客户。 But i would like, that laoding the dependent data (devices) starts, after loading the data refereing to (customers) has finished.但我想,在加载引用(客户)的数据完成后,开始加载依赖数据(设备)。 I think i need to use promises, but how to implement concrete in the following code situation?我认为我需要使用承诺,但是如何在以下代码情况下实现具体?

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;
  }
}

You can pass a callback to any of 'load' functions, so:您可以将回调传递给任何“加载”函数,因此:

This code:这段代码:

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();
  }

Change to this code:更改为此代码:

loadBaseData() {
    this.loadCustomers(() => {
        this.loadDevices();
    });
  }

And call this callback inside your request.onload :并在您的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 ...

You can make a synchronous ajax call like below.您可以像下面一样进行synchronous ajax调用。 So it waits for the response before executing the next statements.所以它在执行下一条语句之前等待响应。

xhr.open("POST",url,false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM