How do I return the value from callback function and pass it to resolve function in Graphql?
Here's the dummy code to show the concept:
This function runs the sql query:
function runQuery(query, cb){
....
var value = "Something";
cb(null, value);
}
This takes the value from callback function pass it to resolve function in graphql:
function getTitle() {
return runQuery("...", function(err, value){
return value;
});
}
Graphql schema:
var SampleType = new GraphQLObjectType({
name: 'Sample',
fields: () => ({
title: { type: GraphQLString },
}),
});
query: new GraphQLObjectType({
name: 'Query',
fields: () => ({
sample: {
type: SampleType,
resolve: () => getTitle(),
},
}),
}),
You can make use of promises and async
to accomplish this.
async function getTitle() {
const queryResult = await runQuery("...");
// ...
// Do post-query stuff here that you currently have in your callback
// ...
return queryResult
}
async function runQuery() {
const value = 'something';
// ...
return value;
}
Node fully supports async/await as of 7.10.0. Use TypeScript or Babel if you're in the browser or are locked into a lower version of node.