How to return value from callback in Graphql resolve function?

Viewed 4855

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(),
      },
    }),
  }),
2 Answers

Basically you can create a promise around that runQuery so that you can use async await when using the query data

const getTitle = () => {
    return new Promise((resolve, reject) => {
       runQuery("...", (error, response) => !error
           ? resolve(response)
           : reject(error))
    })
}

const asyncFunction = async () => {
    const data = await getTitle()
        .then((response) => {
            // handle response and return what you want
            return response.data
        })
        .catch((error) => {
            // handle error, log it, etc, in whatever way you want
            console.log(error.message)
            return null
        })
    if(data) { // data is valid
        // do what you want with the valid data (no error)
    } else { // there was an error
        // handle if there is an error
    }
}

asyncFunction()
Related