Ville Miekk-oja Ville Miekk-oja - 2 months ago 8
Node.js Question

NodeJS combine chaining sync and async functions with then

I have a main function that is used to perform a specific query and parse the response. The first step in that function is validating the parameters given to that function. Then I will generate the query, sign it and then send it. For last, I will handle the response.

For sending the query, I would want to use the promise pattern. What I would want is that the main function would return a promise. The problem is, that most of the functions are sync and not async, so I shouldn't use promise. What I would want is something like this:

return this.validateQueryAttributes(attributes)
.then(generateQuery)
.then(signQuery)
.then(sendQuery)
.then(handleResponse);


Problem is, that the first function doesn't return a promise. So I cannot chain it with the other functions with then, as the then pattern expects to get a promise. Also, I have a .catch function one level up, that I want to use to catch error conditions that can happen in any of those functions that I'm calling. If I wouldn't chain the first function with the rest, then errors happening in the first function would not be catched?

Answer

You can use Promise.resolve() to start a promise chain and then use synchronous (and possibly throwing) functions as then handlers:

return Promise.resolve(attributes)
  .then(this.validateQueryAttributes) // you might need .bind(this)
  .then(generateQuery)
  .then(signQuery)
  .then(sendQuery)
  .then(handleResponse);

Alternatively, if you are using a library such as Bluebird, you can also use Promise.try or Promise.method to catch synchronous exceptions.