Is it possible to add a handle to a promise such that it gets executed at the end of the promise chain. I know there is done() and finally(), but they execute after the current promise is resolved/fails, not the whole chain.

EDIT: The actual case is: Basically I have a function allocating a db connection and executing a db query, and returns a promise that gets resolved when the query completes, passing the connection and result. The function also sets up a query method on the connection that returns another promise, so queries can be chained on the same db connection by calling the query method from a then() handler and returning the returned promise. The db connection has to be free once all handles are done. Currently I just require the user of the function to manually free the connection in the last then(), and I auto-free it in error handlers.

有帮助吗?

解决方案

To be blunt: No.

there is no way to detect the end promise chain. Especially since you can add things later:

var original = delay(500).then(delay(100);
// when is original done?
setTimeout(function(){
    var p = original.then(function(){ return delay(1000);});
    if(Math.random() > 0.5) p = p.then(function(){ return delay(1000); });
});

The only way is to do something close is to nest:

myPromise().then(function(){
    return promise2().then(promise3).then(promise4);
}).finally(function(){
    // all promises done here
});

Edit after clarification:

Bluebird promises experimentally allow Promise.using, which would let you dispose connections like you'd want. This is somewhat similar to using( in C# except asynchronous.

Here's an example from the API:

function getConnection(){
    return pool.getConnectionAsync().disposer(function(conn,out){
        conn.releaseToPool();
    });
}

Promise.using(getConnection(), function(connection) {
   return connection.queryAsync("SELECT * FROM TABLE");
}).then(function(rows) {
    console.log(rows);
});

In this case, the connection closes as soon as the query finishes (that is, the inner chaining is complete). The big advantage is that you don't have to remember to use .end is you get connections with using.

Official support will land in 2.0 soon.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top