简体   繁体   中英

Why my async function returns an undefined when i try to access it?

I am sorry I do not know so well asynchronous javascript but I hope u can help me with this. I want to get results from Wordpress rest API in an asynchronous way.

 async getResults() {
    let thePages = [];
    let thePosts = [];
  // GET PAGES      
    await this.getJSON(`${schoolData.root_url}/wp-json/wp/v2/pages?search=${this.input.value}`, (err, pages) => {
      if (err != null) {
        console.error('Pages error: ', err);
      } else {
        thePages.push(pages);
        console.log('This is from getResults function: ', pages);
      }
    });

    // GET POSTS
    await this.getJSON(`${schoolData.root_url}/wp-json/wp/v2/posts?search=${this.input.value}`, (err, posts) => {
      if (err != null) {
        console.error('Posts error: ', err);
      } else {
        thePosts.push(posts);
        console.log('This is from getResults function: ', posts);
      }
    });

    return this.createResults(thePosts, thePosts)

  }

  createResults(posts, pages) {
    let thePosts = posts;
    let thePages = pages;
    console.log('This is from create results function: ', thePosts[0], thePages);
   }

   getJSON(url, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function () {
      let status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status, xhr.response);
      }
    };
    xhr.send();
   };

This is my output:

This is from create results function:  undefined, []0: (4) [{…}, {…}, {…}, {…}]length: 1__proto__: Array(0) 
This is from getResults function:  (4) [{…}, {…}, {…}, {…}]
This is from getResults function:  (2) [{…}, {…}]

I want to get output something like from Results function

Now I understood that await needed a promise. I changed the getJson function, now it returns a promise. It works)

async getResults() {
    let thePages = await this.httpGet(`${schoolData.root_url}/wp-json/wp/v2/pages?search=${this.input.value}`);
    let thePosts = await this.httpGet(`${schoolData.root_url}/wp-json/wp/v2/posts?search=${this.input.value}`);

    return this.createResults(JSON.parse(thePosts), JSON.parse(thePages));
  }

createResults(posts, pages) {
    this.resultsDiv.innerHTML = `
      <span class="search-content-title">Новости :</span>
      ${posts.length > 0 ? '<ul class="search-content-links">' : '<p class="err">Нет подходящих результатов</p>' }
      ${posts.map(i => `<li><a href="${i.link}">${i.title.rendered}</a></li>`).join('')}
      ${posts.length > 0 ? '</ul>' : ''}

      <span class="search-content-title">Страницы :</span>
      ${pages.length > 0 ? '<ul class="search-content-links">' : '<p class="err">Нет подходящих результатов</p>' }
      ${pages.map(i => `<li><a href="${i.link}">${i.title.rendered}</a></li>`).join('')}
      ${pages.length > 0 ? '</ul>' : ''}
    `;

    return this.isSpinnerVisible = false;
 }

httpGet(url) {

    return new Promise(function(resolve, reject) {

      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);

      xhr.onload = function() {
        if (this.status == 200) {
          resolve(this.response);
        } else {
          var error = new Error(this.statusText);
          error.code = this.status;
          reject(error);
        }
      };

      xhr.onerror = function() {
        reject(new Error("Network Error"));
      };

      xhr.send();
    });

  }

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