Alin
Alin

Reputation: 14571

Chaining functions that return promises in js

The idea is that I need to run multiple operations against the database, but only if I need to. For instance if there are no items to insert, then there is no insert call.

function dbOperations(params){
    functionInsert(params)
    .then(functionUpdate(params))
    .then(functionDelete(params))
    ...
}

then I have

function functionInsert(params){
  if (params){
    //DO a call against DB which returns a promise 
   return knex.insert().transacting(trx);
  }else{
    //if no params, no need to do anything, just let the next .then() fire next function
    return Promise.resolve()
  }
}

By having it like that, the code runs fine but when there are no params then I see this warning Warning: .then() only accepts functions but was passed: [object Object] so it's obvious I am doing something wrong.

How should this scenario be handled, when there are no params?

LE: for db access I am using knex. I've edited the functionInsert above.

Upvotes: 1

Views: 83

Answers (1)

31piy
31piy

Reputation: 23859

The warning itself is explaining. .then expects a function as its argument, but you're passing the result of the function functionUpdate instead.

You may want to wrap the statement(s) in anonymous functions instead, as pointed out by @Thilo in the comments:

function dbOperations(params){
    functionInsert(params)
      .then(() => functionUpdate(params))
      .then(() => functionDelete(params))
      ...
}

Upvotes: 1

Related Questions