简体   繁体   中英

Why doesn't Javascript/Angular let this function finish before it continues on?

I have a function within a component that calls a service to get an http response. In the below method (which calls the service):

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

it is going ahead and executing the console.log before the result is even back from the called function. Why is calling this method (getSearchResults) not a synchronous operation (even though the method being called does asynchronous http action, the return doesn't occur until that's done). Also, what is the recommended way to handle this so result is back before proceeding?

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;

        });
  }

JavaScript wont stop until API finish so you should use promises to get the result only after the API returned/finished. Here is an example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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