Graphql 如何从knex插入中获取ID?
我使用下面的代码作为graphql解析器的一部分。我试图从knex查询返回id,但console.logpageid返回为null,但console.logid没有返回 resolveparentValue,{id,页面名称,页面类型,页面类别}{ var pageid=null; 常数pageInsert=knex .插入{id,页面名称,页面类型,页面类别} .返回'id' .进入“页面” .Then函数id{ console.logid; pageid=id; }; console.logpageid; console.logpageInsert; 返回页面插入; }Graphql 如何从knex插入中获取ID?,graphql,knex.js,Graphql,Knex.js,我使用下面的代码作为graphql解析器的一部分。我试图从knex查询返回id,但console.logpageid返回为null,但console.logid没有返回 resolveparentValue,{id,页面名称,页面类型,页面类别}{ var pageid=null; 常数pageInsert=knex .插入{id,页面名称,页面类型,页面类别} .返回'id' .进入“页面” .Then函数id{ console.logid; pageid=id; }; console.log
我将在javascript中注释这些行的执行顺序:
resolve(parentValue, { id, page_name, page_type, page_category }) {
var pageid = null; // -- 1 page id is null
const pageInsert = knex
.insert({ id, page_name, page_type, page_category })
.returning('id')
.into('page')
.then(function (id) {
console.log(id); // -- 6 printing result just file
pageid = id; // -- 7 storing result to variable that is never used
}); // -- 2 created query builder and triggered it's execution
console.log(pageid); // -- 3 pageid is still null
console.log(pageInsert); // -- 4 page insert is a promise which is returned
return pageInsert; // -- 5
}
所以你要把它取回来,然后把它存储到一个局部变量pageid中,之后就再也不用了
你可能应该做的只是:
resolve(parentValue, { id, page_name, page_type, page_category }) {
return knex
.insert({ id, page_name, page_type, page_category })
.returning('id')
.into('page')
}
在呼叫端:
resolve(...).then(id => console.log(id))
or
const id = await resolve(...);