简体   繁体   English

是否有可能检测到承诺链的结束

[英]Is it possible to detect end of promise chain

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. 我知道有done()finally() ,但是它们在当前的承诺解决/失败之后执行,而不是在整个链上执行。

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. 编辑:实际情况是:基本上我有一个分配db连接并执行db查询的函数,并返回一个诺言,该诺言在查询完成时得到解析,并传递连接和结果。 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. 该函数还在返回另一个诺言的连接上设置查询方法,因此可通过从then()处理程序中调用查询方法并返回返回的诺言来将查询链接到同一数据库连接上。 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. 目前,我只要求函数的用户在最后的then()中手动释放连接,然后在错误处理程序中自动释放该连接。

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. 蓝鸟承诺在实验上允许Promise.using ,这将使您可以Promise.using处置连接。 This is somewhat similar to using( in C# except asynchronous. 除了异步以外,这与C#中的using(类似。

Here's an example from the API: 这是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 . 最大的优点是您不必记住要使用.end ,您可以使用using获得联系。

Official support will land in 2.0 soon. 官方支持即将在2.0中提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM