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