如何在Graphql解析函数中从回调中返回值?

时间:2017-05-31 20:22:31

标签: javascript graphql relayjs relay graphql-js

如何从回调函数返回值并将其传递给Graphql中的resolve函数?

这里是显示概念的虚拟代码:

此函数运行sql查询:

function runQuery(query, cb){
   ....
   var value = "Something";
   cb(null, value);
}

这将从回调函数传递它来解析graphql中的函数:

function getTitle() {
   return runQuery("...", function(err, value){ 
             return value; 
          });
}

Graphql架构:

var SampleType = new GraphQLObjectType({
  name: 'Sample',
  fields: () => ({
    title: { type: GraphQLString },
  }),
});


query: new GraphQLObjectType({
    name: 'Query',
    fields: () => ({
      sample: {
        type: SampleType,
        resolve: () => getTitle(),
      },
    }),
  }),

2 个答案:

答案 0 :(得分:1)

您可以使用promises和async来完成此任务。

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

节点fully supports async/await as of 7.10.0。如果您在浏览器中或被锁定在较低版本的节点中,请使用TypeScript或Babel。

答案 1 :(得分:0)

const getTitle = () => {
    return new Promise(() => {
       runQuery("...", (error, value) => {
          if(error)
            resolve(null) // on error value
          resolve(value)
       })
    })
}