如何将交易系统构建到 .then() 链中?

How to build a transaction system into a .then() chain?

我的代码中有多个链式同步请求。我正在使用 NodeJS 包请求承诺。

这里有一些伪代码来展示它是如何格式化的:

initRequest.then(function(response){
    return request2;
}).then(function(response2){
    return request3;
}).then(function(response3){
    return requestN;
}).catch(function(err){
    log(error)
});

例如,如果 request3 失败,会发生什么情况?链条是继续,还是完全跳出循环?

如果request2 是POST,而request3 失败了,有没有办法系统地回滚request2 更改的数据?

谢谢。

Does the chain continue, or does it break out of the loop completely?

它中断并继续到 catchfinally proposal,它在最近的 Node.js 版本中可用,在旧版本中可填充 - 类似于 try..catch..finally 对同步的工作方式代码(这也是将普通承诺转换为 async 函数的方式)。

And if request2 was a POST, and request3 failed, is there a way to systematically roll back the data that request2 changed?

这应该由开发人员保护。如果有可能回滚数据,则应将必要的信息(数据条目 ID)保存到变量中并在 catch.

中回滚

如果 request3 失败,它将停止执行其余的请求链。

并且无法系统地回滚 request2 更改的内容,您必须以自定义方式实施它。

request3失败时处理,自己捕获request3。 这是 simple/mini 处理 request3 失败

的方法
initRequest.then(function(response){
    return request2;
}).then(function(response2){
    return request3.catch(function(err2){
        //if something goes wrong do rollback
        request2Rollback.then(rollbackRes => {
            throw new Error("request3 failed! roll backed request 2!");
        }).catch(function(err){
            // the rollback itself has failed so do something serious here
            throw err;
        })
    });;
}).then(function(response3){
    return requestN;
}).catch(function(err){
    log(error)
});