问题描述
所以我有2个API:
localhost:8080 / projects(为我提供我拥有的项目的列表)
localhost:8080 / tasks / {projectid}(为我提供了与我用作参数的项目ID相关的任务列表)
我正在使用nodejs来获取第一个API的结果,然后将它们插入JSON数组中,同时从同一请求中获取每个ID,并在第二个api中使用它们来获取任务,最后我会提取这些任务,并将其插入与项目相同的JSON数组中。
但是我遇到了一个问题,在完成操作后,我试图显示JSON数组只是为了发现它仅包含项目名称(这是第一个API的结果),而没有找到来自第二个的信息。
这是我使用的方法:
首先,我制作了2种方法,一种用于获取项目,一种用于获取任务,我在两种方法中都使用了回调:
const projects = (callback) =>{
const url='localhost:8080/projects'
request({url,json:true},(error,{body}) =>{
if(error){
callback('error')
}else{
callback(undefined,body)
}
})
}
const tasks = (projectid,callback) =>{
const url='localhost:8080/tasks/'+encodeURIComponent(projectid)
request({url,{body})=>{
if(error){
callback('unable to find data')
}else{
callback(undefined,body)
= }
})
}
然后我使用express为这两种方法定义路由:
app.get('/projects',(req,res)=>{
func.projects((error,body)=>{
if(error){
return res.send({
error : error
})
}
res.send(body)
})
})
app.get('/tasks',res)=>{
func.tasks(req.query.code,body)=>{
if(error){
return res.send({
error : error
})
}
res.send(body)
})
})
最后,我尝试使用Javascript将这2条路由中的数据提取到json数组中,并在handlabars页面中显示它们:
fetch('/projects').then((response) => {
response.json().then((res) => {
if (res.error) {
console.log(res.error)
} else {
data = { todo: [] }
//insert each project into our json array
res.forEach((project) => {
data.todo.push({ id: project.id,text: project.id })
//Now we'll get the tasks using the project id as argument
fetch('/tasks?code='+encodeURIComponent(project.id)).then((response)=>{
response.json().then((res)=>{
if(res.error){
console.log(error)
} else {
//add each task to the same array
res.forEach((task) => {
data.todo.push({text: task.desc,parent: item.id})
})
}
})
})
})
gantt.parse(data);
}
})
})
很抱歉,我只想解释所有细节。谢谢。
编辑:我的程序的目标是将json文件用作甘特图的参数,这就是为什么我调用了名为甘特的函数的原因,当我传递json对象时,该函数仅显示项目,但现在显示任务。
即使使用console.log函数,它也表明我的对象确实包含任务。我认为这里的问题是该函数同时执行两个foreach,这就是为什么它不返回任务的原因,因为它还没有必需的参数
解决方法
我希望您了解fetch
是异步的,这就是为什么您有一个then
块的原因,该块在异步操作完成后执行代码。我已经以您的示例为例,然后添加了带有数字的内嵌注释,这些注释指示执行的流程。
// 1. Starts execution.
fetch('/projects').then((response) => {
response.json().then((res) => {
if (res.error) {
console.log(res.error)
} else {
// 2. Res has the list of projects.
data = { todo: [] }
//insert each project into our json array
res.forEach((project) => {
data.todo.push({ id: project.id,text: project.id })
// 3. Fetch is called for each project.
//Now we'll get the tasks using the project id as argument
fetch('/tasks?code='+encodeURIComponent(project.id)).then((response)=>{
response.json().then((res)=>{
if(res.error){
console.log(error)
} else {
// 5. Data is push is to the array.
//add each task to the same array
res.forEach((task) => {
data.todo.push({text: task.desc,parent: item.id})
})
}
})
})
})
// 4. parse is called.
gantt.parse(data);
}
})
})
如您所见,gantt.parse(data)
在数据到达后续提取请求之前被调用。这意味着您必须等待所有请求完成后才能调用gantt.parse(data)
。您可以为此使用Promise.all
。
您还提到console.log
显示了数据。这是因为console.log
通常通过引用起作用。尝试console.log(JSON.stringify(data))
,您会看到丢失的数据。
为解决这个问题,我将使用Promise.all
通过公共API添加一个示例。
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(todos => {
// I'm just taking the first 5 todos.
todos = todos.slice(0,5);
const data = {
todos: []
};
const requests = [];
todos.forEach(todo => {
data.todos.push({
id: todo.id,title: todo.title
});
requests.push(fetchComments(todo.id));
});
Promise.all(requests).then(responses => {
console.log(data);
// Here is where you will call gnatt.parse
});
function fetchComments(id) {
return fetch(`https://jsonplaceholder.typicode.com/todos/${id}/comments`)
.then(res => res.json()).then(comments => {
comments.forEach(comment => {
data.todos.push({
id: comment.id,parent: id
});
});
});
}
});