【问题标题】:Create method chain before object exists在对象存在之前创建方法链
【发布时间】:2018-11-14 18:52:20
【问题描述】:

假设我正在使用knex 对 SQL 数据库运行查询。我链接了一些方法来构建查询。

例如:

const sqlConfig = require('./sql.config');

var knex = require('knex')(sqlConfig);

knex.select("*")
  .from("books")
  .where("author", "=", "José Saramago")
  .then((rows) => {
    console.log(rows);
  })
  .catch((err) => {
    console.log(err);
  })
  .finally(() => {
    knex.destroy();
  })

现在,我的问题是:

有没有办法在knex对象创建之前存储方法链,然后在创建时调用它?

类似这样的:

const methodChain = <<<
  .select("*"),
  .from("books"),
  .where("author", "=", "José Saramago")
>>>

const sqlConfig = require('./sql.config');

var knex = require('knex')(sqlConfig);

knex
  .methodChain()
  .then((rows) => {
    console.log(rows);
  })
  .catch((err) => {
    console.log(err);
  })
  .finally(function() {
    knex.destroy();
  })

【问题讨论】:

    标签: javascript method-chaining


    【解决方案1】:

    您可以创建一个接受链中初始参数的函数:

    function methodChain(in) {
      return in.select("*")
               .from("books")
               .where("author", "=", "José Saramago");
    }
    
    methodChain(knex)
      .then((rows) => {
        console.log(rows);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(function() {
        knex.destroy();
      })
    

    【讨论】:

    • 这可以通过删除methodChain 中的逗号来实现。我确定你是从我的问题中复制过来的,我的错。谢谢!
    • @EdgarR.Mondragón 你说得对,我错过了!很高兴它对你有用,我现在已经删除了多余的逗号。
    【解决方案2】:

    当然。

    const methodChain = (x) => x
        .select("*"),
        .from("books"),
        .where("author", "=", "José Saramago");
    

    后来

    methodChain(knex)
      .then((rows) => {
        console.log(rows);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(function() {
        knex.destroy();
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多