首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何等待http请求的结果(同步http请求,http请求作为promise)

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

Stack Overflow用户
提问于 2020-08-21 17:10:04
回答 2查看 165关注 0票数 0

我有一个typescript服务,它通过服务器的htpp请求加载基本数据。有几个对几个数据的请求,从不相关的数据到依赖于数据的数据的顺序排列,加载ist启动了bevor。因为异步http请求不能保证通过请求(例如下面例子中的客户)加载数据已经完成,所以开始加载依赖于它的数据(例如下面例子中的设备),并且我不能将加载设备指代被加载的客户。但我想,加载依赖数据(设备)开始后,加载引用(客户)的数据已完成。我认为我需要使用promises,但是在下面的代码情况下如何实现具体的代码呢?

代码语言:javascript
复制
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;
  }
}
EN

回答 2

Stack Overflow用户

发布于 2020-08-21 17:20:53

您可以将回调传递给任何“load”函数,因此:

这段代码:

代码语言:javascript
复制
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();
  }

更改此代码:

代码语言:javascript
复制
loadBaseData() {
    this.loadCustomers(() => {
        this.loadDevices();
    });
  }

并在request.onload中调用此回调

代码语言:javascript
复制
// 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 ...
票数 0
EN

Stack Overflow用户

发布于 2020-08-21 17:21:47

您可以像下面这样进行synchronous ajax调用。因此,在执行下一条语句之前,它会等待响应。

代码语言:javascript
复制
xhr.open("POST",url,false);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63519876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档