gpt4 book ai didi

javascript - 如何从需要返回语句的 GraphQL 解析器中调用异步 node.js 函数?

转载 作者:数据小太阳 更新时间:2023-10-29 05:07:08 24 4
gpt4 key购买 nike

graphql.org/graphql-js 上提供的 Hello World 示例创建一个简单的 GraphQL 实现如下:

var { graphql, buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);

// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello World!';
}
};

// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
console.log(response);
});

我正在尝试在解析器中运行一个异步函数,例如数据库调用,但我似乎无法弄清楚如何让它工作:

我正在尝试做的事情:

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);
});

我试过使用 promises,但似乎没有办法在不进入回调的情况下逃避 promises。我还尝试了各种包装异步 getData 函数以强制它同步的方法,但最终不得不从异步函数返回一个值,同样的问题。我觉得这不可能这么复杂,我的意思是 GraphQL-JS 是由 Facebook 编写的。

最佳答案

所以这个问题原来是你在弄清楚之后会觉得很愚蠢的问题之一,但由于我花了很长时间来解决这个问题,所以我会回答我自己的问题,这样其他人就有希望从中受益。

事实证明,GraphQL 解析器函数必须返回一个值或解析为该值的 promise 。所以我试图用这样的东西来做:

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);
});

可以这样来完成:

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);
});

关于javascript - 如何从需要返回语句的 GraphQL 解析器中调用异步 node.js 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com