问题描述
需要一些帮助.假设我要以下数据:
need some help. Let say Im requesting the following data:
{
parent {
obj1 {
value1
}
obj2 {
value2
}
}
}
我需要使用value1解析器中value2的结果进行计算.
And I need the result of value2 in value1 resolver for calculation.
应该在value2中返回承诺并以某种方式将其放入value1解析器中,但是如果value2解析器尚未运行怎么办?
Thought of returning a promise in in value2 and somehow take it in value1 resolver, but what if value2 resolver didn’t run yet?
有什么办法可以做到吗?
There`s any way it could be done?
推荐答案
我立即想到的是,您可以使用上下文来实现类似的目的.我以为您可以将像对象这样的缓存与事件发射器混合在一起,以解决竞争条件问题.
My immediate thought is that you could use the context to achieve something like this. I'd imagine you could have a cache like object mixed with an event emitter to solve the race condition issue.
例如,假设我们有一些课程
For example, assume we had some class
class CacheEmitter extends EventEmitter {
constructor() {
super();
this.cache = {};
}
get(key) {
return new Promise((resolve, reject) => {
// If value2 resolver already ran.
if (this.cache[key]) {
return resolve(this.cache[key]);
}
// If value2 resolver has not already run.
this.on(key, (val) => {
resolve(val);
});
})
}
put(key, value) {
this.cache[key] = value;
this.emit(key, value);
}
}
然后从您的解析器中,您可以执行以下操作.
Then from your resolvers you could do something like this.
value1Resolver: (parent, args, context, info) => {
return context.cacheEmitter.get('value2').then(val2 => {
doSomethingWithValue2();
});
}
value2Resolver: (parent, args, context, info) => {
return doSomethingToFetch().then(val => {
context.cacheEmitter.put('value2', val);
return val;
}
}
我还没有尝试过,但这似乎对我有用!如果您试一试,我很好奇,所以让我知道它是否有效.仅出于记账目的,您需要确保实例化"CacheEmitter"类并将其提供给顶层的GraphQL上下文.
I haven't tried it but that seems like it may work to me! If you give it a shot, I'm curious so let me know if it works. Just for book keeping you would need to make sure you instantiate the 'CacheEmitter' class and feed it into the GraphQL context at the top level.
希望这会有所帮助:)
这篇关于GraphQL:从同级解析器访问另一个解析器/字段输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!