Joymaker
Joymaker

Reputation: 1428

Javascript: return promise after promise chaining

JavaScript newbie question here: I want to be able to write a function that participates in a promise chain, while doing some promise chaining within it. After the last promise within the chain results, I want to return that promise so that a chain outside the function can continue. Here's my example code. The interesting part is pseudocoded in line 10,

    .then(now return this promise);

what is the correct syntax or methodology for doing this?

function setUpConnection() {
  // do whatever
  return client;
}

function doSomeQueries(client) {
  client.query("doSomeSqlHere")
    .then(client.query, "doSomeMoreSqlHere")
    .then(client.query, "do a third query")
    .then(now return this promise);
}

client = setupConnection();
client.connect()
  .then(doSomeQueries(client))
  .then(client.close());

Upvotes: 0

Views: 84

Answers (1)

yevt
yevt

Reputation: 816

I remember how I wanted to chain everything when I just started using promises, and how I was shocked by the simplicity of the understanding that it's not required. You can stop chaining and save reference to any point of the chain

function doSomeQueries(client) {
  let promise = client.query("doSomeSqlHere")
    .then(client.query, "doSomeMoreSqlHere")
    .then(client.query, "do a third query")
  return promise; // you can return either Promise<Value> or Value here
}

client = setupConnection();
client.connect()
  .then(doSomeQueries(client))
  .then(client.close());

Upvotes: 1

Related Questions