对不起,我不太了解异步 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 函数中得到类似的输出
最佳答案
现在我明白 await 需要一个 promise 。我更改了 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();
});
}
关于javascript - 为什么我的异步函数在我尝试访问它时返回未定义的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171899/