Почему моя асинхронная функция возвращает неопределенное значение, когда я пытаюсь получить к ней доступ? - PullRequest
0 голосов
/ 13 января 2019

Извините, я не очень хорошо знаю асинхронный 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 голосов
/ 17 января 2019

Теперь я понял, что ждать нужно обещание. Я изменил функцию getJson, теперь она возвращает обещание. Работает)

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

  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...