How do I call an asynchronous node.js function from within a GraphQL resolver requiring a return statement?

前端 未结 1 1989
陌清茗
陌清茗 2021-02-20 00:40

The Hello World example provided on graphql.org/graphql-js for creating a simple GraphQL implementation is the following:

var { graphql, buildSchema } = require(         


        
相关标签:
1条回答
  • 2021-02-20 01:20

    So this one turned out to be one of those problems you feel really stupid about after you figure it out, but because of how long I spent struggling with it, I'll answer my own question so someone else can hopefully benefit.

    It turns out the GraphQL resolver function has to return either a value or a promise that resolves to that value. So what I was trying to do with something like this:

    var { graphql, buildSchema } = require('graphql');
    
    // Construct a schema, using GraphQL schema language
    var schema = buildSchema(`
        type Query {
            data: String
        }
    `);
    
    // The root provides a resolver function for each API endpoint
    var root = {
        data: () => {
            getData((data) => {
                return data;    // Returns from callback, instead of from resolver
            }
        }
    };
    
    // Run the GraphQL query '{ data }' and print out the response
    graphql(schema, '{ data }', root).then((response) => {
        console.log(response);
    });
    

    Can be done with something like this:

    var { graphql, buildSchema } = require('graphql');
    
    // Construct a schema, using GraphQL schema language
    var schema = buildSchema(`
        type Query {
            data: String
        }
    `);
    
    let promiseData = () => {
        return new Promise((resolve, reject) => {
            getData((data) => {
                resolve(data);
            });
        });
    };
    
    // The root provides a resolver function for each API endpoint
    var root = {
        data: () => {
            return promiseData();
        }
    };
    
    // Run the GraphQL query '{ data }' and print out the response
    graphql(schema, '{ data }', root).then((response) => {
        console.log(response);
    });
    
    0 讨论(0)
提交回复
热议问题