我正在使用此功能修改本地存储的变量(数据),并且它可以正常工作。但由于它尚未设置Promise,因此在页面加载后检索数据,因此不会显示。我已经经历了几次迭代,尝试使用Promise来使其正常工作,但是无法正确使用。
我假设应该有一个Promise.all用于projects.map区域,但是我不知道它在哪里被解析,以及它是如何被调用的。
function getProjects() {
fetch('http://localhost:8888/wp-json/wp/v2/categories')
.then(r => r.json())
.then(categories => {
categories.forEach(category => {
data.forEach(service => {
if(service.service_name == category.name) {
fetch(`http://localhost:8888/wp-json/wp/v2/projects?
categories=${category.id}`)
.then(r => r.json())
.then(projects => {
service.projects = projects.map(project => {
// if true, add PROJECT to THAT service
if(project.better_featured_image) {
return {
project_name: project.title.rendered,
project_desc: project.content.rendered,
project_img:
project.better_featured_image.media_details.sizes.medium.source_url
}
} else {
return {
project_name: project.title.rendered,
project_desc: project.content.rendered
}
}
})
})
}
})
})
})
}
将var数据设置为这样,以便每个项目都需要根据类别附加到服务。
var data = [
{
service_name: 'Service 1',
service_desc: 'Desc',
service_img: 'Img URL',
projects: [
{
project_name: 'Project 1',
project_desc: 'Desc',
project_img: 'Img URL'
}
}
]
答案 0 :(得分:0)
使用Promise.all()
function getProjects() {
fetch('http://localhost:8888/wp-json/wp/v2/categories')
.then(r => r.json())
.then(categories => {
var promises = [];
categories.forEach(category => {
data.forEach(service => {
if (service.service_name == category.name) {
promises.push(fetch(`http://localhost:8888/wp-json/wp/v2/projects?categories=${category.id}`)
.then(r => r.json()));
}
})
})
return Promise.all(promises)
}).then(data => {
// Get result of all call
})
}