0

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?

Ville Miekk-oja
  • 18,749
  • 32
  • 70
  • 106
  • 2
    Yes, but you should never return a promise if the function itself is sync. You should only use promises for async functions. – Ville Miekk-oja Sep 09 '16 at 09:27
  • Would that be the best practise in this situation? If you think yes, please post it as an answer. And how to make that async wrapper :) – Ville Miekk-oja Sep 09 '16 at 09:34

1 Answers1

1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375