如何从 Graphql 解析函数中的回调中获取 return 值?

How to return value from callback in Graphql resolve function?

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

这是展示概念的虚拟代码:

此函数运行 sql 查询:

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

这从回调函数中获取值并将其传递给 graphql 中的 resolve 函数:

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

您可以使用 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。

基本上你可以围绕那个 runQuery 创建一个承诺,这样你就可以在使用查询数据时使用异步等待

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()