将graphql字段实现为函数是否表示JavaScript中闭包或提升行为的使用?
我最近一直在研究graphql,我发现要在我的模式中实现循环引用,我需要将我的字段属性声明为将graphql字段实现为函数是否表示JavaScript中闭包或提升行为的使用?,javascript,express,graphql,closures,hoisting,Javascript,Express,Graphql,Closures,Hoisting,我最近一直在研究graphql,我发现要在我的模式中实现循环引用,我需要将我的字段属性声明为thunk或函数,引用它可以帮助我理解这一点 请允许我引用这个答案 假设文件中有两种类型,它们相互引用 BookType有一个字段author,并引用AuthorType。现在,假设您在BookType引用BookType下定义了AuthorType 因此,当Javascript引擎需要使用BookType时,它会看到字段.author.type是AuthorType并且上面没有定义AuthorType。
thunk
或函数
,引用它可以帮助我理解这一点
请允许我引用这个答案
假设文件中有两种类型,它们相互引用
BookType
有一个字段author,并引用AuthorType
。现在,假设您在BookType
引用BookType
下定义了AuthorType
因此,当Javascript引擎需要使用BookType
时,它会看到字段.author.type
是AuthorType
并且上面没有定义AuthorType
。因此它将给出引用错误:未定义AuthorType
因此,BookType
的正确实现是
const BookType= new GraphQLObjectType({
name: 'BookType',
fields: () => { // as a thunk -> the correct implementation
author: {
type: AuthorType,
resolve: (parentValue, args) => {
// query the author based on your db implementation.
}
}
}
});
我需要知道的是,将字段属性定义为thunk
,对于循环引用或其自身类型的引用,描述JavaScript的用法
是提升还是闭合还是两者兼而有之?是的,@Bergi你能解释一下为什么它是闭合的用法吗。我只看到提升的用法?如果JavaScript中没有闭包且只有提升可用,调用arrow函数会抱怨
未声明的变量“AuthorType”
@Bergi,因为它既不是参数,也不是在函数中定义的。
const AuthorType= new GraphQLObjectType({
name: 'AuthorType',
fields: { // as object
books: {
type: new GraphQLList(BookType), //one author might have multiple books
resolve: (parentValue, args) => {
// query the books based on your db implementation.
}
}
}
});
const BookType= new GraphQLObjectType({
name: 'BookType',
fields: () => { // as a thunk -> the correct implementation
author: {
type: AuthorType,
resolve: (parentValue, args) => {
// query the author based on your db implementation.
}
}
}
});