Azure / azure-cosmosdb-js-server

The JavaScript SDK for server-side programming in Azure Cosmos DB
MIT License
178 stars 153 forks source link

Support for Promises in Stored Procedures #15

Closed theodiefenthal closed 6 years ago

theodiefenthal commented 7 years ago

Hi there,

I just started using JavaScript for developing a transactional StoredProcedure in DocumentDB.

It seemed for me to be the best choice to use Promises instead of callbacks in designing my procedure. However, I just realized that I am sadly not able to rollback my transactions / throw errors when using promises.

The problem is:

Once I'm inside a promise, I cannot "throw errors out" of it to the execution engine. See this: http://stackoverflow.com/a/33446005 or even better this one: http://stackoverflow.com/questions/30715367/why-can-i-not-throw-inside-a-promise-catch-handler

They suggest some, in my oppinion, dirty hacks by just throwing the exception from another call stack in order to avoid the promise letting catch it. I don't see a possibility to do this in DocumentDB StoredProcedure as well, as setTimeout() seems not to work on another call stack and I don't see a way to work with listeners or find a somehow other way to let a function run on a different callstack.

What I would like to have is one of the following: Create a function to "kill" the stored procedure and rollback the transaction like getContext().getResponse().reject(errorMsg) or likely even better, just evaluate if my stored procedure returns a promise, and if, wait for that result and when it is in an error state, rollback the transaction and throw an exception (in my java SDK) like you would, if I would throw an error.

leftler commented 6 years ago

Can someone from the team respond about this, I am running in to the same issue with having pyramids of doom on my stored procedures.

ghost commented 6 years ago

Agreed, I'm running into the same issue. I would realy like to use promises, (clearer flow, in my opinion) but this is preventing me from doing so in the stored procedures.

jnonce commented 6 years ago

Has this been addressed in a recent update? I see a new method in the server side js docs: https://azure.github.io/azure-cosmosdb-js-server/Context.html

abort(err) Terminates the script and rolls back the transaction. The script is executed in the context of a transaction, which can be rolled back by using this method. This method is the only way to prevent script transaction from committing in promise callback.

getContext().abort(new Error('abort'));
mkolt commented 6 years ago

yes, abort API was to target this issue.