为什么Javascript / Angular在继续运行之前不让此功能完成?

时间:2019-12-07 18:38:46

标签: javascript angular http

我在组件中有一个函数,该函数调用服务以获取http响应。在以下方法(调用服务)中:

getSearchResults() {
    let result = this.service.getSearchResults(this.searchValues, this.ITEMSPERPAGE);
    console.log(result);
  }

它正在继续执行console.log,直到结果从被调用函数返回。为什么调用此方法(getSearchResults)不是同步操作(即使被调用的方法执行异步http动作,也要等到完成后才返回)。另外,建议使用什么方法来处理此问题,以便在继续操作之前返回结果?

getSearchResults(searchValues, itemsPerPage : number, page : number = 1) {
    let results = {
        studentList: null,
        errorResult: null,
        pages: null,
        totalPages: null
    };
    let searchCriterions = {};
    Object.keys(searchValues).forEach(a => {
      if (searchValues[a] != null && searchValues[a] != '') {
        searchCriterions[a] = searchValues[a];
      }
    }
    );
    searchCriterions['itemsPerPage'] = itemsPerPage.toString();
    searchCriterions['page'] = page;

    this.httpClient.get("http://localhost:8080/data/alumni/search",
      {
        params: searchCriterions
      }).subscribe(data => { 
          results.studentList = data; 


      if (page == 1) {
        this.httpClient.get("http://localhost:8080/data/alumni/search/pageCount",
          {
            params: searchCriterions
          }).subscribe(data => {

            results.pages = Array(Math.ceil(data['pageCount'] / itemsPerPage));
            results.totalPages = results.pages.length;
            console.log(results);
            return results;



          }, error => 
          {
              results.errorResult = error;
              return results;

          });
        } 
        else {
            return results;
        }

        }, error => 
        {
            results.errorResult = error;
            return results;

        });
  }

1 个答案:

答案 0 :(得分:-1)

JavaScript直到API完成后才会停止,因此仅在API返回/完成后,才应使用promises来获得结果。这是一个示例:

search(term:string) {
  let promise = new Promise((resolve, reject) => {
    let apiURL = `${this.apiRoot}?term=${term}&media=music&limit=20`;
    this.http.get(apiURL)
      .toPromise()
      .then(
        res => { // Success
          console.log(res.json());
          resolve();
        }
      );
  });
  return promise;
}