【发布时间】:2019-04-25 09:52:59
【问题描述】:
我有一些我想从 graphiql gui 中查看的虚拟数据(书籍)。但是,当我使用forEach 循环遍历书籍,寻找特定的id 时,它会返回未定义的值,但如果我使用普通的for 循环,它就可以正常工作。
这是我的代码:
let books = [
{ name: 'Name of the Wind', genre: 'Horror', id: '1', authorID: '3' },
{ name: 'The Final Empire', genre: 'Fantasy', id: '2', authorID: '1' },
{ name: 'The Long Earth', genre: 'Sci-Fi', id: '3', authorID: '2' },
];
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLString } },
//this forEach is not working
resolve(parent, args){
books.forEach( function(book) {
if(book.id == args.id) {
console.log(book);
return book;
}
});
}
}
}
});
当我打印出图书数据时,它会在控制台中显示该特定图书,但不会在 GUI 响应中显示:
request:
{
book(id: "2") {
name
genre
}
}
response:
{
"data": {
"book": null
}
}
【问题讨论】:
-
forEach从不返回任何东西
标签: javascript loops foreach graphql