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

落爺英雄遲暮 提交于 2019-12-04 05:18:30

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);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!