如何从knex插入件取回ID?

时间:2019-05-01 19:33:07

标签: graphql knex.js

我将下面的代码用作graphql解析器的一部分。我正在尝试从knex查询返回id,但是console.log(pageid)返回为null。但是console.log(id)不是;

library(grid)
p <- p <- ggplot(iris, aes(Petal.Length, Sepal.Length)) + 
  geom_point() + 
  facet_wrap(~ Species, nrow = 3)

grobs <- ggplotGrob(p)

multi <- cbind(grobs, grobs, grobs, size = "first")

grid.newpage(); grid.draw(multi)

1 个答案:

答案 0 :(得分:0)

我将注释在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
}

因此,您将其恢复到.then中,但随后将其存储到局部变量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(...);