为什么我尝试访问异步函数时会返回一个未定义的?

时间:2019-01-13 18:28:38

标签: javascript async-await

对不起,我不太了解异步javascript,但希望您能对此提供帮助。我想以异步方式从Wordpress rest API获取结果。

 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 from create results function:  undefined, []0: (4) [{…}, {…}, {…}, {…}]length: 1__proto__: Array(0) 
This is from getResults function:  (4) [{…}, {…}, {…}, {…}]
This is from getResults function:  (2) [{…}, {…}]

我想从Results函数获得类似的输出

1 个答案:

答案 0 :(得分:0)

现在我了解到等待需要一个诺言。我更改了getJson函数,现在它返回了一个promise。有效)

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

  }